shng2025 commited on
Commit
f2137f8
·
verified ·
1 Parent(s): cbcc3ce

RunACTStaged + scripted insert v1 (SC scene 004, gt off)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. README.md +49 -0
  3. checkpoints/align/config.json +79 -0
  4. checkpoints/align/model.safetensors +3 -0
  5. checkpoints/align/policy_postprocessor.json +32 -0
  6. checkpoints/align/policy_postprocessor_step_0_unnormalizer_processor.safetensors +3 -0
  7. checkpoints/align/policy_preprocessor.json +72 -0
  8. checkpoints/align/policy_preprocessor_step_3_normalizer_processor.safetensors +3 -0
  9. checkpoints/align/train_config.json +209 -0
  10. checkpoints/approach/config.json +79 -0
  11. checkpoints/approach/model.safetensors +3 -0
  12. checkpoints/approach/policy_postprocessor.json +32 -0
  13. checkpoints/approach/policy_postprocessor_step_0_unnormalizer_processor.safetensors +3 -0
  14. checkpoints/approach/policy_preprocessor.json +72 -0
  15. checkpoints/approach/policy_preprocessor_step_3_normalizer_processor.safetensors +3 -0
  16. checkpoints/approach/train_config.json +209 -0
  17. checkpoints/guarded_insert/config.json +79 -0
  18. checkpoints/guarded_insert/model.safetensors +3 -0
  19. checkpoints/guarded_insert/policy_postprocessor.json +32 -0
  20. checkpoints/guarded_insert/policy_postprocessor_step_0_unnormalizer_processor.safetensors +3 -0
  21. checkpoints/guarded_insert/policy_preprocessor.json +72 -0
  22. checkpoints/guarded_insert/policy_preprocessor_step_3_normalizer_processor.safetensors +3 -0
  23. checkpoints/guarded_insert/train_config.json +209 -0
  24. checkpoints/retry_or_finish/config.json +79 -0
  25. checkpoints/retry_or_finish/model.safetensors +3 -0
  26. checkpoints/retry_or_finish/policy_postprocessor.json +32 -0
  27. checkpoints/retry_or_finish/policy_postprocessor_step_0_unnormalizer_processor.safetensors +3 -0
  28. checkpoints/retry_or_finish/policy_preprocessor.json +72 -0
  29. checkpoints/retry_or_finish/policy_preprocessor_step_3_normalizer_processor.safetensors +3 -0
  30. checkpoints/retry_or_finish/train_config.json +209 -0
  31. docs/technique.md +142 -0
  32. policy/aic_example_policies/__init__.py +0 -0
  33. policy/aic_example_policies/ros/RunACT.py +2027 -0
  34. policy/aic_example_policies/ros/RunACTCompetitor.py +468 -0
  35. policy/aic_example_policies/ros/RunACTStaged.py +1431 -0
  36. policy/aic_example_policies/ros/RunACTStagedScriptedInsert.py +110 -0
  37. policy/aic_example_policies/ros/__init__.py +0 -0
  38. policy/aic_example_policies/ros/canonical_episode_writer.py +107 -0
  39. policy/aic_example_policies/ros/sfp_tuning_profiles.py +26 -0
  40. policy/aic_example_policies/ros/vision_target_features.py +1549 -0
  41. policy_env.txt +10 -0
  42. results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/policy_env.txt +12 -0
  43. results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/bag_trial_1_20261027_012629_993/bag_trial_1_20261027_012629_993_0.mcap +3 -0
  44. results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/bag_trial_1_20261027_012629_993/metadata.yaml +78 -0
  45. results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/scoring.yaml +27 -0
  46. results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/policy_env.txt +12 -0
  47. results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/bag_trial_1_20261027_012730_159/bag_trial_1_20261027_012730_159_0.mcap +3 -0
  48. results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/bag_trial_1_20261027_012730_159/metadata.yaml +78 -0
  49. results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/scoring.yaml +27 -0
  50. results/runs/stitch-a0-base-t3-004-gtoff-20261027_012816/policy_env.txt +12 -0
.gitattributes CHANGED
@@ -33,3 +33,40 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/bag_trial_1_20261027_012629_993/bag_trial_1_20261027_012629_993_0.mcap filter=lfs diff=lfs merge=lfs -text
37
+ results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/bag_trial_1_20261027_012730_159/bag_trial_1_20261027_012730_159_0.mcap filter=lfs diff=lfs merge=lfs -text
38
+ results/runs/stitch-a0-base-t3-004-gtoff-20261027_012816/results/bag_trial_1_20261027_012830_337/bag_trial_1_20261027_012830_337_0.mcap filter=lfs diff=lfs merge=lfs -text
39
+ results/runs/stitch-a1-stiff800-t1-004-gtoff-20261027_012916/results/bag_trial_1_20261027_012930_596/bag_trial_1_20261027_012930_596_0.mcap filter=lfs diff=lfs merge=lfs -text
40
+ results/runs/stitch-a1-stiff800-t2-004-gtoff-20261027_013005/results/bag_trial_1_20261027_013018_750/bag_trial_1_20261027_013018_750_0.mcap filter=lfs diff=lfs merge=lfs -text
41
+ results/runs/stitch-a1-stiff800-t3-004-gtoff-20261027_013104/results/bag_trial_1_20261027_013118_009/bag_trial_1_20261027_013118_009_0.mcap filter=lfs diff=lfs merge=lfs -text
42
+ results/runs/stitch-a2-smallfast-t1-004-gtoff-20261027_013204/results/bag_trial_1_20261027_013218_306/bag_trial_1_20261027_013218_306_0.mcap filter=lfs diff=lfs merge=lfs -text
43
+ results/runs/stitch-a2-smallfast-t2-004-gtoff-20261027_013303/results/bag_trial_1_20261027_013317_512/bag_trial_1_20261027_013317_512_0.mcap filter=lfs diff=lfs merge=lfs -text
44
+ results/runs/stitch-a2-smallfast-t3-004-gtoff-20261027_013404/results/bag_trial_1_20261027_013417_696/bag_trial_1_20261027_013417_696_0.mcap filter=lfs diff=lfs merge=lfs -text
45
+ results/runs/stitch-a3-both-t1-004-gtoff-20261027_013452/results/bag_trial_1_20261027_013505_987/bag_trial_1_20261027_013505_987_0.mcap filter=lfs diff=lfs merge=lfs -text
46
+ results/runs/stitch-a3-both-t2-004-gtoff-20261027_013551/results/bag_trial_1_20261027_013605_170/bag_trial_1_20261027_013605_170_0.mcap filter=lfs diff=lfs merge=lfs -text
47
+ results/runs/stitch-a3-both-t3-004-gtoff-20261027_013643/results/bag_trial_1_20261027_013657_397/bag_trial_1_20261027_013657_397_0.mcap filter=lfs diff=lfs merge=lfs -text
48
+ results/runs/stitch-scripted3-t1-004-gtoff-20261027_010905/results/bag_trial_1_20261027_010919_304/bag_trial_1_20261027_010919_304_0.mcap filter=lfs diff=lfs merge=lfs -text
49
+ results/runs/stitch-scripted3-t2-004-gtoff-20261027_010957/results/bag_trial_1_20261027_011011_326/bag_trial_1_20261027_011011_326_0.mcap filter=lfs diff=lfs merge=lfs -text
50
+ results/runs/stitch-scripted3-t3-004-gtoff-20261027_011036/results/bag_trial_1_20261027_011050_436/bag_trial_1_20261027_011050_436_0.mcap filter=lfs diff=lfs merge=lfs -text
51
+ results/runs/video-scripted-insert-004-gtoff-20261027_011815/results/bag_trial_1_20261027_011835_209/bag_trial_1_20261027_011835_209_0.mcap filter=lfs diff=lfs merge=lfs -text
52
+ results/runs/video-scripted-insert-004-gtoff-20261027_011922/results/bag_trial_1_20261027_011942_607/bag_trial_1_20261027_011942_607_0.mcap filter=lfs diff=lfs merge=lfs -text
53
+ results/runs/video-scripted-insert-004-gtoff-20261027_012030/results/bag_trial_1_20261027_012050_148/bag_trial_1_20261027_012050_148_0.mcap filter=lfs diff=lfs merge=lfs -text
54
+ results/runs/video-scripted-insert-004-gtoff-20261027_012136/results/bag_trial_1_20261027_012156_878/bag_trial_1_20261027_012156_878_0.mcap filter=lfs diff=lfs merge=lfs -text
55
+ results/runs/video-scripted-insert-004-gtoff-20261027_012244/results/bag_trial_1_20261027_012304_305/bag_trial_1_20261027_012304_305_0.mcap filter=lfs diff=lfs merge=lfs -text
56
+ results/runs/video-scripted-insert-004-gtoff-20261027_012351/results/bag_trial_1_20261027_012411_576/bag_trial_1_20261027_012411_576_0.mcap filter=lfs diff=lfs merge=lfs -text
57
+ results/runs/video-scripted-insert-004-gtoff-20261027_012459/results/bag_trial_1_20261027_012519_150/bag_trial_1_20261027_012519_150_0.mcap filter=lfs diff=lfs merge=lfs -text
58
+ results/runs/video-scripted-insert-004-gtoff-20261027_071454/results/bag_trial_1_20261027_071515_685/bag_trial_1_20261027_071515_685_0.mcap filter=lfs diff=lfs merge=lfs -text
59
+ results/runs/video-scripted-insert-004-gtoff-20261027_071603/results/bag_trial_1_20261027_071623_344/bag_trial_1_20261027_071623_344_0.mcap filter=lfs diff=lfs merge=lfs -text
60
+ results/runs/video-scripted-insert-004-gtoff-20261027_071711/results/bag_trial_1_20261027_071731_836/bag_trial_1_20261027_071731_836_0.mcap filter=lfs diff=lfs merge=lfs -text
61
+ results/runs/video-scripted-insert-004-gtoff-20261027_071808/results/bag_trial_1_20261027_071828_045/bag_trial_1_20261027_071828_045_0.mcap filter=lfs diff=lfs merge=lfs -text
62
+ results/runs/video-scripted-insert-004-gtoff-20261027_071915/results/bag_trial_1_20261027_071935_972/bag_trial_1_20261027_071935_972_0.mcap filter=lfs diff=lfs merge=lfs -text
63
+ results/runs/video-scripted-insert-004-gtoff-20261027_072024/results/bag_trial_1_20261027_072044_811/bag_trial_1_20261027_072044_811_0.mcap filter=lfs diff=lfs merge=lfs -text
64
+ results/runs/video-scripted-insert-004-gtoff-20261027_072133/results/bag_trial_1_20261027_072153_388/bag_trial_1_20261027_072153_388_0.mcap filter=lfs diff=lfs merge=lfs -text
65
+ results/runs/video-scripted-insert-004-gtoff-20261027_072241/results/bag_trial_1_20261027_072301_265/bag_trial_1_20261027_072301_265_0.mcap filter=lfs diff=lfs merge=lfs -text
66
+ results/runs/video-scripted-insert-004-gtoff-20261027_072348/results/bag_trial_1_20261027_072409_023/bag_trial_1_20261027_072409_023_0.mcap filter=lfs diff=lfs merge=lfs -text
67
+ results/runs/video-scripted-insert-004-gtoff-20261027_072457/results/bag_trial_1_20261027_072517_571/bag_trial_1_20261027_072517_571_0.mcap filter=lfs diff=lfs merge=lfs -text
68
+ results/runs/video-scripted-insert-004-gtoff-20261027_072605/results/bag_trial_1_20261027_072625_429/bag_trial_1_20261027_072625_429_0.mcap filter=lfs diff=lfs merge=lfs -text
69
+ results/runs/video-scripted-insert-004-gtoff-20261027_072714/results/bag_trial_1_20261027_072734_444/bag_trial_1_20261027_072734_444_0.mcap filter=lfs diff=lfs merge=lfs -text
70
+ results/runs/video-scripted-insert-004-gtoff-20261027_072823/results/bag_trial_1_20261027_072842_873/bag_trial_1_20261027_072842_873_0.mcap filter=lfs diff=lfs merge=lfs -text
71
+ results/runs/video-scripted-insert-004-gtoff-20261027_072918/results/bag_trial_1_20261027_072938_393/bag_trial_1_20261027_072938_393_0.mcap filter=lfs diff=lfs merge=lfs -text
72
+ results/runs/video-scripted-insert-004-gtoff-20261027_073026/results/bag_trial_1_20261027_073046_310/bag_trial_1_20261027_073046_310_0.mcap filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: lerobot
3
+ pipeline_tag: robotics
4
+ tags:
5
+ - act
6
+ - robotics
7
+ - lerobot
8
+ - intrinsic-ai-challenge
9
+ - cable-insertion
10
+ ---
11
+
12
+ # Quantarune ACT-FSM: SC scripted insert (v1)
13
+
14
+ ```
15
+ quantarune-act-fsm-sc-scripted-insert/ 2.7G
16
+ ├── README.md
17
+ ├── policy_env.txt runtime env of a full-insertion take
18
+ ├── policy/aic_example_policies/ros/ 252K policy code (v1 snapshot + parents)
19
+ ├── checkpoints/ 790M 4 stage ACT models, step 10000
20
+ │ ├── approach/
21
+ │ ├── align/
22
+ │ ├── guarded_insert/
23
+ │ └── retry_or_finish/
24
+ ├── training/ 252K stage dataset build + training scripts
25
+ │ ├── quantarune_training/
26
+ │ └── quantarune_teleop/
27
+ ├── results/ 1.9G
28
+ │ ├── trials.csv 37 trials: batch, setting, score
29
+ │ └── runs/<run>/ scoring.yaml, policy_env.txt, bag
30
+ └── docs/technique.md 20K full write-up
31
+ ```
32
+
33
+ This repo holds the best SC cable insertion result of Project Automaton so far. It is part of the 2026 Intrinsic AI for Industry Challenge in Gazebo. A four-stage ACT finite state machine brings the SC plug to the port lip. A scripted wiggle-descent then pushes the plug into the seat. Ground truth is off in every trial here. Code, weights, results and the write-up are all in this one repo.
34
+
35
+ ## Scope and results
36
+
37
+ The results cover the SC port only. They also cover one scene only, `sc_scripted_smoke_001_004`. The v1 default setting reached a full insertion in 4 of 28 trials (14%). All 37 trials, including 9 trials with tuned finish settings, reached a full insertion in 7 cases (19%). A full insertion scores about 97.7 of 100. Each failed trial stopped about 13 mm above the seat and scored about 60.
38
+
39
+ ## How it works
40
+
41
+ `RunACTStagedScriptedInsert` subclasses `RunACTStaged`, which wraps four ACT checkpoints in an FSM. The stages are APPROACH, ALIGN, GUARDED_INSERT and RETRY_OR_FINISH. When the guarded insert gives up, the scripted finish takes over from the current pose. It descends at 4 mm/s at 400 N/m with a small circular wiggle. It reads no port pose. `docs/technique.md` gives the full pipeline and the failure analysis.
42
+
43
+ ## Known limits
44
+
45
+ The policy stops when it sees `/scoring/insertion_event` from the scorer. We have not yet confirmed that this signal is legal in the official evaluation. The v1 finish also has a known bug with stiffness. It sets the stiffness to 400 N/m and never resets it. The engine reuses one policy object across trials, so trial 2 of a multi-trial run would approach at 400 N/m. Every trial here ran in its own single-trial run, and the next version fixes this bug.
46
+
47
+ ## Run it
48
+
49
+ Put `policy/aic_example_policies` on `PYTHONPATH` next to the AIC toolkit packages. Load the policy as `aic_example_policies.ros.RunACTStagedScriptedInsert`. Set the variables in `policy_env.txt` and point the four checkpoint paths at `checkpoints/<stage>/`. `RunACT.py` keeps the Apache 2.0 header of Intrinsic Innovation LLC from the toolkit example. The training datasets are not in this repo yet, and they will follow later.
checkpoints/align/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "act",
3
+ "n_obs_steps": 1,
4
+ "input_features": {
5
+ "observation.images.center_camera": {
6
+ "type": "VISUAL",
7
+ "shape": [
8
+ 3,
9
+ 256,
10
+ 288
11
+ ]
12
+ },
13
+ "observation.images.left_camera": {
14
+ "type": "VISUAL",
15
+ "shape": [
16
+ 3,
17
+ 256,
18
+ 288
19
+ ]
20
+ },
21
+ "observation.images.right_camera": {
22
+ "type": "VISUAL",
23
+ "shape": [
24
+ 3,
25
+ 256,
26
+ 288
27
+ ]
28
+ },
29
+ "observation.state": {
30
+ "type": "STATE",
31
+ "shape": [
32
+ 48
33
+ ]
34
+ }
35
+ },
36
+ "output_features": {
37
+ "action": {
38
+ "type": "ACTION",
39
+ "shape": [
40
+ 19
41
+ ]
42
+ }
43
+ },
44
+ "device": "cuda",
45
+ "use_amp": false,
46
+ "use_peft": false,
47
+ "push_to_hub": false,
48
+ "repo_id": null,
49
+ "private": null,
50
+ "tags": null,
51
+ "license": null,
52
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
53
+ "chunk_size": 100,
54
+ "n_action_steps": 100,
55
+ "normalization_mapping": {
56
+ "VISUAL": "MEAN_STD",
57
+ "STATE": "MEAN_STD",
58
+ "ACTION": "MEAN_STD"
59
+ },
60
+ "vision_backbone": "resnet18",
61
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
62
+ "replace_final_stride_with_dilation": false,
63
+ "pre_norm": false,
64
+ "dim_model": 512,
65
+ "n_heads": 8,
66
+ "dim_feedforward": 3200,
67
+ "feedforward_activation": "relu",
68
+ "n_encoder_layers": 4,
69
+ "n_decoder_layers": 1,
70
+ "use_vae": true,
71
+ "latent_dim": 32,
72
+ "n_vae_encoder_layers": 4,
73
+ "temporal_ensemble_coeff": null,
74
+ "dropout": 0.1,
75
+ "kl_weight": 10.0,
76
+ "optimizer_lr": 1e-05,
77
+ "optimizer_weight_decay": 0.0001,
78
+ "optimizer_lr_backbone": 1e-05
79
+ }
checkpoints/align/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b112571e76f40b5fec1a283c6a2169fa21d5d0d2556017fa60470db074af6fa4
3
+ size 206925068
checkpoints/align/policy_postprocessor.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_postprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "unnormalizer_processor",
6
+ "config": {
7
+ "eps": 1e-08,
8
+ "features": {
9
+ "action": {
10
+ "type": "ACTION",
11
+ "shape": [
12
+ 19
13
+ ]
14
+ }
15
+ },
16
+ "norm_map": {
17
+ "VISUAL": "MEAN_STD",
18
+ "STATE": "MEAN_STD",
19
+ "ACTION": "MEAN_STD"
20
+ }
21
+ },
22
+ "state_file": "policy_postprocessor_step_0_unnormalizer_processor.safetensors"
23
+ },
24
+ {
25
+ "registry_name": "device_processor",
26
+ "config": {
27
+ "device": "cpu",
28
+ "float_dtype": null
29
+ }
30
+ }
31
+ ]
32
+ }
checkpoints/align/policy_postprocessor_step_0_unnormalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03984e0f3756df0631fc1264bfff179c2909f1244430fcd9dcc6d253e95601db
3
+ size 10844
checkpoints/align/policy_preprocessor.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_preprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "rename_observations_processor",
6
+ "config": {
7
+ "rename_map": {}
8
+ }
9
+ },
10
+ {
11
+ "registry_name": "to_batch_processor",
12
+ "config": {}
13
+ },
14
+ {
15
+ "registry_name": "device_processor",
16
+ "config": {
17
+ "device": "cuda",
18
+ "float_dtype": null
19
+ }
20
+ },
21
+ {
22
+ "registry_name": "normalizer_processor",
23
+ "config": {
24
+ "eps": 1e-08,
25
+ "features": {
26
+ "observation.images.center_camera": {
27
+ "type": "VISUAL",
28
+ "shape": [
29
+ 3,
30
+ 256,
31
+ 288
32
+ ]
33
+ },
34
+ "observation.images.left_camera": {
35
+ "type": "VISUAL",
36
+ "shape": [
37
+ 3,
38
+ 256,
39
+ 288
40
+ ]
41
+ },
42
+ "observation.images.right_camera": {
43
+ "type": "VISUAL",
44
+ "shape": [
45
+ 3,
46
+ 256,
47
+ 288
48
+ ]
49
+ },
50
+ "observation.state": {
51
+ "type": "STATE",
52
+ "shape": [
53
+ 48
54
+ ]
55
+ },
56
+ "action": {
57
+ "type": "ACTION",
58
+ "shape": [
59
+ 19
60
+ ]
61
+ }
62
+ },
63
+ "norm_map": {
64
+ "VISUAL": "MEAN_STD",
65
+ "STATE": "MEAN_STD",
66
+ "ACTION": "MEAN_STD"
67
+ }
68
+ },
69
+ "state_file": "policy_preprocessor_step_3_normalizer_processor.safetensors"
70
+ }
71
+ ]
72
+ }
checkpoints/align/policy_preprocessor_step_3_normalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03984e0f3756df0631fc1264bfff179c2909f1244430fcd9dcc6d253e95601db
3
+ size 10844
checkpoints/align/train_config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": {
3
+ "repo_id": "align",
4
+ "root": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/act_stage_datasets/sc_stage_fixed_scene_curated_001_2026-05-05_00-48-03/datasets/align",
5
+ "episodes": null,
6
+ "image_transforms": {
7
+ "enable": false,
8
+ "max_num_transforms": 3,
9
+ "random_order": false,
10
+ "tfs": {
11
+ "brightness": {
12
+ "weight": 1.0,
13
+ "type": "ColorJitter",
14
+ "kwargs": {
15
+ "brightness": [
16
+ 0.8,
17
+ 1.2
18
+ ]
19
+ }
20
+ },
21
+ "contrast": {
22
+ "weight": 1.0,
23
+ "type": "ColorJitter",
24
+ "kwargs": {
25
+ "contrast": [
26
+ 0.8,
27
+ 1.2
28
+ ]
29
+ }
30
+ },
31
+ "saturation": {
32
+ "weight": 1.0,
33
+ "type": "ColorJitter",
34
+ "kwargs": {
35
+ "saturation": [
36
+ 0.5,
37
+ 1.5
38
+ ]
39
+ }
40
+ },
41
+ "hue": {
42
+ "weight": 1.0,
43
+ "type": "ColorJitter",
44
+ "kwargs": {
45
+ "hue": [
46
+ -0.05,
47
+ 0.05
48
+ ]
49
+ }
50
+ },
51
+ "sharpness": {
52
+ "weight": 1.0,
53
+ "type": "SharpnessJitter",
54
+ "kwargs": {
55
+ "sharpness": [
56
+ 0.5,
57
+ 1.5
58
+ ]
59
+ }
60
+ },
61
+ "affine": {
62
+ "weight": 1.0,
63
+ "type": "RandomAffine",
64
+ "kwargs": {
65
+ "degrees": [
66
+ -5.0,
67
+ 5.0
68
+ ],
69
+ "translate": [
70
+ 0.05,
71
+ 0.05
72
+ ]
73
+ }
74
+ }
75
+ }
76
+ },
77
+ "revision": null,
78
+ "use_imagenet_stats": true,
79
+ "video_backend": "pyav",
80
+ "streaming": false
81
+ },
82
+ "env": null,
83
+ "policy": {
84
+ "type": "act",
85
+ "n_obs_steps": 1,
86
+ "input_features": {
87
+ "observation.images.center_camera": {
88
+ "type": "VISUAL",
89
+ "shape": [
90
+ 3,
91
+ 256,
92
+ 288
93
+ ]
94
+ },
95
+ "observation.images.left_camera": {
96
+ "type": "VISUAL",
97
+ "shape": [
98
+ 3,
99
+ 256,
100
+ 288
101
+ ]
102
+ },
103
+ "observation.images.right_camera": {
104
+ "type": "VISUAL",
105
+ "shape": [
106
+ 3,
107
+ 256,
108
+ 288
109
+ ]
110
+ },
111
+ "observation.state": {
112
+ "type": "STATE",
113
+ "shape": [
114
+ 48
115
+ ]
116
+ }
117
+ },
118
+ "output_features": {
119
+ "action": {
120
+ "type": "ACTION",
121
+ "shape": [
122
+ 19
123
+ ]
124
+ }
125
+ },
126
+ "device": "cuda",
127
+ "use_amp": false,
128
+ "use_peft": false,
129
+ "push_to_hub": false,
130
+ "repo_id": null,
131
+ "private": null,
132
+ "tags": null,
133
+ "license": null,
134
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
135
+ "chunk_size": 100,
136
+ "n_action_steps": 100,
137
+ "normalization_mapping": {
138
+ "VISUAL": "MEAN_STD",
139
+ "STATE": "MEAN_STD",
140
+ "ACTION": "MEAN_STD"
141
+ },
142
+ "vision_backbone": "resnet18",
143
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
144
+ "replace_final_stride_with_dilation": false,
145
+ "pre_norm": false,
146
+ "dim_model": 512,
147
+ "n_heads": 8,
148
+ "dim_feedforward": 3200,
149
+ "feedforward_activation": "relu",
150
+ "n_encoder_layers": 4,
151
+ "n_decoder_layers": 1,
152
+ "use_vae": true,
153
+ "latent_dim": 32,
154
+ "n_vae_encoder_layers": 4,
155
+ "temporal_ensemble_coeff": null,
156
+ "dropout": 0.1,
157
+ "kl_weight": 10.0,
158
+ "optimizer_lr": 1e-05,
159
+ "optimizer_weight_decay": 0.0001,
160
+ "optimizer_lr_backbone": 1e-05
161
+ },
162
+ "output_dir": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_align/2026-05-06_00-41-13",
163
+ "job_name": "sc_stage_fixed_scene_curated_001_v1_align_2026-05-06_00-41-13",
164
+ "resume": false,
165
+ "seed": 1000,
166
+ "num_workers": 2,
167
+ "batch_size": 8,
168
+ "steps": 10000,
169
+ "eval_freq": 1000000,
170
+ "log_freq": 100,
171
+ "tolerance_s": 0.0001,
172
+ "save_checkpoint": true,
173
+ "save_freq": 2000,
174
+ "use_policy_training_preset": true,
175
+ "optimizer": {
176
+ "type": "adamw",
177
+ "lr": 1e-05,
178
+ "weight_decay": 0.0001,
179
+ "grad_clip_norm": 10.0,
180
+ "betas": [
181
+ 0.9,
182
+ 0.999
183
+ ],
184
+ "eps": 1e-08
185
+ },
186
+ "scheduler": null,
187
+ "eval": {
188
+ "n_episodes": 50,
189
+ "batch_size": 50,
190
+ "use_async_envs": false
191
+ },
192
+ "wandb": {
193
+ "enable": false,
194
+ "disable_artifact": false,
195
+ "project": "lerobot",
196
+ "entity": null,
197
+ "notes": null,
198
+ "run_id": null,
199
+ "mode": null
200
+ },
201
+ "peft": null,
202
+ "use_rabc": false,
203
+ "rabc_progress_path": null,
204
+ "rabc_kappa": 0.01,
205
+ "rabc_epsilon": 1e-06,
206
+ "rabc_head_mode": "sparse",
207
+ "rename_map": {},
208
+ "checkpoint_path": null
209
+ }
checkpoints/approach/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "act",
3
+ "n_obs_steps": 1,
4
+ "input_features": {
5
+ "observation.images.center_camera": {
6
+ "type": "VISUAL",
7
+ "shape": [
8
+ 3,
9
+ 256,
10
+ 288
11
+ ]
12
+ },
13
+ "observation.images.left_camera": {
14
+ "type": "VISUAL",
15
+ "shape": [
16
+ 3,
17
+ 256,
18
+ 288
19
+ ]
20
+ },
21
+ "observation.images.right_camera": {
22
+ "type": "VISUAL",
23
+ "shape": [
24
+ 3,
25
+ 256,
26
+ 288
27
+ ]
28
+ },
29
+ "observation.state": {
30
+ "type": "STATE",
31
+ "shape": [
32
+ 48
33
+ ]
34
+ }
35
+ },
36
+ "output_features": {
37
+ "action": {
38
+ "type": "ACTION",
39
+ "shape": [
40
+ 19
41
+ ]
42
+ }
43
+ },
44
+ "device": "cuda",
45
+ "use_amp": false,
46
+ "use_peft": false,
47
+ "push_to_hub": false,
48
+ "repo_id": null,
49
+ "private": null,
50
+ "tags": null,
51
+ "license": null,
52
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
53
+ "chunk_size": 100,
54
+ "n_action_steps": 100,
55
+ "normalization_mapping": {
56
+ "VISUAL": "MEAN_STD",
57
+ "STATE": "MEAN_STD",
58
+ "ACTION": "MEAN_STD"
59
+ },
60
+ "vision_backbone": "resnet18",
61
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
62
+ "replace_final_stride_with_dilation": false,
63
+ "pre_norm": false,
64
+ "dim_model": 512,
65
+ "n_heads": 8,
66
+ "dim_feedforward": 3200,
67
+ "feedforward_activation": "relu",
68
+ "n_encoder_layers": 4,
69
+ "n_decoder_layers": 1,
70
+ "use_vae": true,
71
+ "latent_dim": 32,
72
+ "n_vae_encoder_layers": 4,
73
+ "temporal_ensemble_coeff": null,
74
+ "dropout": 0.1,
75
+ "kl_weight": 10.0,
76
+ "optimizer_lr": 1e-05,
77
+ "optimizer_weight_decay": 0.0001,
78
+ "optimizer_lr_backbone": 1e-05
79
+ }
checkpoints/approach/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd840408734dd005c15cee343f653fc63b42b699a3617103ae5cd46da0291875
3
+ size 206925068
checkpoints/approach/policy_postprocessor.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_postprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "unnormalizer_processor",
6
+ "config": {
7
+ "eps": 1e-08,
8
+ "features": {
9
+ "action": {
10
+ "type": "ACTION",
11
+ "shape": [
12
+ 19
13
+ ]
14
+ }
15
+ },
16
+ "norm_map": {
17
+ "VISUAL": "MEAN_STD",
18
+ "STATE": "MEAN_STD",
19
+ "ACTION": "MEAN_STD"
20
+ }
21
+ },
22
+ "state_file": "policy_postprocessor_step_0_unnormalizer_processor.safetensors"
23
+ },
24
+ {
25
+ "registry_name": "device_processor",
26
+ "config": {
27
+ "device": "cpu",
28
+ "float_dtype": null
29
+ }
30
+ }
31
+ ]
32
+ }
checkpoints/approach/policy_postprocessor_step_0_unnormalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36abae88a5a6f8a5fe34d78ddb49d6719e7675d43b1a52fcd90e3796da5ffa37
3
+ size 10844
checkpoints/approach/policy_preprocessor.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_preprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "rename_observations_processor",
6
+ "config": {
7
+ "rename_map": {}
8
+ }
9
+ },
10
+ {
11
+ "registry_name": "to_batch_processor",
12
+ "config": {}
13
+ },
14
+ {
15
+ "registry_name": "device_processor",
16
+ "config": {
17
+ "device": "cuda",
18
+ "float_dtype": null
19
+ }
20
+ },
21
+ {
22
+ "registry_name": "normalizer_processor",
23
+ "config": {
24
+ "eps": 1e-08,
25
+ "features": {
26
+ "observation.images.center_camera": {
27
+ "type": "VISUAL",
28
+ "shape": [
29
+ 3,
30
+ 256,
31
+ 288
32
+ ]
33
+ },
34
+ "observation.images.left_camera": {
35
+ "type": "VISUAL",
36
+ "shape": [
37
+ 3,
38
+ 256,
39
+ 288
40
+ ]
41
+ },
42
+ "observation.images.right_camera": {
43
+ "type": "VISUAL",
44
+ "shape": [
45
+ 3,
46
+ 256,
47
+ 288
48
+ ]
49
+ },
50
+ "observation.state": {
51
+ "type": "STATE",
52
+ "shape": [
53
+ 48
54
+ ]
55
+ },
56
+ "action": {
57
+ "type": "ACTION",
58
+ "shape": [
59
+ 19
60
+ ]
61
+ }
62
+ },
63
+ "norm_map": {
64
+ "VISUAL": "MEAN_STD",
65
+ "STATE": "MEAN_STD",
66
+ "ACTION": "MEAN_STD"
67
+ }
68
+ },
69
+ "state_file": "policy_preprocessor_step_3_normalizer_processor.safetensors"
70
+ }
71
+ ]
72
+ }
checkpoints/approach/policy_preprocessor_step_3_normalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36abae88a5a6f8a5fe34d78ddb49d6719e7675d43b1a52fcd90e3796da5ffa37
3
+ size 10844
checkpoints/approach/train_config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": {
3
+ "repo_id": "approach",
4
+ "root": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/act_stage_datasets/sc_stage_fixed_scene_curated_001_2026-05-05_00-48-03/datasets/approach",
5
+ "episodes": null,
6
+ "image_transforms": {
7
+ "enable": false,
8
+ "max_num_transforms": 3,
9
+ "random_order": false,
10
+ "tfs": {
11
+ "brightness": {
12
+ "weight": 1.0,
13
+ "type": "ColorJitter",
14
+ "kwargs": {
15
+ "brightness": [
16
+ 0.8,
17
+ 1.2
18
+ ]
19
+ }
20
+ },
21
+ "contrast": {
22
+ "weight": 1.0,
23
+ "type": "ColorJitter",
24
+ "kwargs": {
25
+ "contrast": [
26
+ 0.8,
27
+ 1.2
28
+ ]
29
+ }
30
+ },
31
+ "saturation": {
32
+ "weight": 1.0,
33
+ "type": "ColorJitter",
34
+ "kwargs": {
35
+ "saturation": [
36
+ 0.5,
37
+ 1.5
38
+ ]
39
+ }
40
+ },
41
+ "hue": {
42
+ "weight": 1.0,
43
+ "type": "ColorJitter",
44
+ "kwargs": {
45
+ "hue": [
46
+ -0.05,
47
+ 0.05
48
+ ]
49
+ }
50
+ },
51
+ "sharpness": {
52
+ "weight": 1.0,
53
+ "type": "SharpnessJitter",
54
+ "kwargs": {
55
+ "sharpness": [
56
+ 0.5,
57
+ 1.5
58
+ ]
59
+ }
60
+ },
61
+ "affine": {
62
+ "weight": 1.0,
63
+ "type": "RandomAffine",
64
+ "kwargs": {
65
+ "degrees": [
66
+ -5.0,
67
+ 5.0
68
+ ],
69
+ "translate": [
70
+ 0.05,
71
+ 0.05
72
+ ]
73
+ }
74
+ }
75
+ }
76
+ },
77
+ "revision": null,
78
+ "use_imagenet_stats": true,
79
+ "video_backend": "pyav",
80
+ "streaming": false
81
+ },
82
+ "env": null,
83
+ "policy": {
84
+ "type": "act",
85
+ "n_obs_steps": 1,
86
+ "input_features": {
87
+ "observation.images.center_camera": {
88
+ "type": "VISUAL",
89
+ "shape": [
90
+ 3,
91
+ 256,
92
+ 288
93
+ ]
94
+ },
95
+ "observation.images.left_camera": {
96
+ "type": "VISUAL",
97
+ "shape": [
98
+ 3,
99
+ 256,
100
+ 288
101
+ ]
102
+ },
103
+ "observation.images.right_camera": {
104
+ "type": "VISUAL",
105
+ "shape": [
106
+ 3,
107
+ 256,
108
+ 288
109
+ ]
110
+ },
111
+ "observation.state": {
112
+ "type": "STATE",
113
+ "shape": [
114
+ 48
115
+ ]
116
+ }
117
+ },
118
+ "output_features": {
119
+ "action": {
120
+ "type": "ACTION",
121
+ "shape": [
122
+ 19
123
+ ]
124
+ }
125
+ },
126
+ "device": "cuda",
127
+ "use_amp": false,
128
+ "use_peft": false,
129
+ "push_to_hub": false,
130
+ "repo_id": null,
131
+ "private": null,
132
+ "tags": null,
133
+ "license": null,
134
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
135
+ "chunk_size": 100,
136
+ "n_action_steps": 100,
137
+ "normalization_mapping": {
138
+ "VISUAL": "MEAN_STD",
139
+ "STATE": "MEAN_STD",
140
+ "ACTION": "MEAN_STD"
141
+ },
142
+ "vision_backbone": "resnet18",
143
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
144
+ "replace_final_stride_with_dilation": false,
145
+ "pre_norm": false,
146
+ "dim_model": 512,
147
+ "n_heads": 8,
148
+ "dim_feedforward": 3200,
149
+ "feedforward_activation": "relu",
150
+ "n_encoder_layers": 4,
151
+ "n_decoder_layers": 1,
152
+ "use_vae": true,
153
+ "latent_dim": 32,
154
+ "n_vae_encoder_layers": 4,
155
+ "temporal_ensemble_coeff": null,
156
+ "dropout": 0.1,
157
+ "kl_weight": 10.0,
158
+ "optimizer_lr": 1e-05,
159
+ "optimizer_weight_decay": 0.0001,
160
+ "optimizer_lr_backbone": 1e-05
161
+ },
162
+ "output_dir": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06",
163
+ "job_name": "sc_stage_fixed_scene_curated_001_v1_approach_2026-05-06_00-36-06",
164
+ "resume": false,
165
+ "seed": 1000,
166
+ "num_workers": 2,
167
+ "batch_size": 8,
168
+ "steps": 10000,
169
+ "eval_freq": 1000000,
170
+ "log_freq": 100,
171
+ "tolerance_s": 0.0001,
172
+ "save_checkpoint": true,
173
+ "save_freq": 2000,
174
+ "use_policy_training_preset": true,
175
+ "optimizer": {
176
+ "type": "adamw",
177
+ "lr": 1e-05,
178
+ "weight_decay": 0.0001,
179
+ "grad_clip_norm": 10.0,
180
+ "betas": [
181
+ 0.9,
182
+ 0.999
183
+ ],
184
+ "eps": 1e-08
185
+ },
186
+ "scheduler": null,
187
+ "eval": {
188
+ "n_episodes": 50,
189
+ "batch_size": 50,
190
+ "use_async_envs": false
191
+ },
192
+ "wandb": {
193
+ "enable": false,
194
+ "disable_artifact": false,
195
+ "project": "lerobot",
196
+ "entity": null,
197
+ "notes": null,
198
+ "run_id": null,
199
+ "mode": null
200
+ },
201
+ "peft": null,
202
+ "use_rabc": false,
203
+ "rabc_progress_path": null,
204
+ "rabc_kappa": 0.01,
205
+ "rabc_epsilon": 1e-06,
206
+ "rabc_head_mode": "sparse",
207
+ "rename_map": {},
208
+ "checkpoint_path": null
209
+ }
checkpoints/guarded_insert/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "act",
3
+ "n_obs_steps": 1,
4
+ "input_features": {
5
+ "observation.images.center_camera": {
6
+ "type": "VISUAL",
7
+ "shape": [
8
+ 3,
9
+ 256,
10
+ 288
11
+ ]
12
+ },
13
+ "observation.images.left_camera": {
14
+ "type": "VISUAL",
15
+ "shape": [
16
+ 3,
17
+ 256,
18
+ 288
19
+ ]
20
+ },
21
+ "observation.images.right_camera": {
22
+ "type": "VISUAL",
23
+ "shape": [
24
+ 3,
25
+ 256,
26
+ 288
27
+ ]
28
+ },
29
+ "observation.state": {
30
+ "type": "STATE",
31
+ "shape": [
32
+ 48
33
+ ]
34
+ }
35
+ },
36
+ "output_features": {
37
+ "action": {
38
+ "type": "ACTION",
39
+ "shape": [
40
+ 19
41
+ ]
42
+ }
43
+ },
44
+ "device": "cuda",
45
+ "use_amp": false,
46
+ "use_peft": false,
47
+ "push_to_hub": false,
48
+ "repo_id": null,
49
+ "private": null,
50
+ "tags": null,
51
+ "license": null,
52
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
53
+ "chunk_size": 100,
54
+ "n_action_steps": 100,
55
+ "normalization_mapping": {
56
+ "VISUAL": "MEAN_STD",
57
+ "STATE": "MEAN_STD",
58
+ "ACTION": "MEAN_STD"
59
+ },
60
+ "vision_backbone": "resnet18",
61
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
62
+ "replace_final_stride_with_dilation": false,
63
+ "pre_norm": false,
64
+ "dim_model": 512,
65
+ "n_heads": 8,
66
+ "dim_feedforward": 3200,
67
+ "feedforward_activation": "relu",
68
+ "n_encoder_layers": 4,
69
+ "n_decoder_layers": 1,
70
+ "use_vae": true,
71
+ "latent_dim": 32,
72
+ "n_vae_encoder_layers": 4,
73
+ "temporal_ensemble_coeff": null,
74
+ "dropout": 0.1,
75
+ "kl_weight": 10.0,
76
+ "optimizer_lr": 1e-05,
77
+ "optimizer_weight_decay": 0.0001,
78
+ "optimizer_lr_backbone": 1e-05
79
+ }
checkpoints/guarded_insert/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14695dbd6437cca04abd374ce6bdeb6718ea607427aec80f01ffe6eae8f53905
3
+ size 206925068
checkpoints/guarded_insert/policy_postprocessor.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_postprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "unnormalizer_processor",
6
+ "config": {
7
+ "eps": 1e-08,
8
+ "features": {
9
+ "action": {
10
+ "type": "ACTION",
11
+ "shape": [
12
+ 19
13
+ ]
14
+ }
15
+ },
16
+ "norm_map": {
17
+ "VISUAL": "MEAN_STD",
18
+ "STATE": "MEAN_STD",
19
+ "ACTION": "MEAN_STD"
20
+ }
21
+ },
22
+ "state_file": "policy_postprocessor_step_0_unnormalizer_processor.safetensors"
23
+ },
24
+ {
25
+ "registry_name": "device_processor",
26
+ "config": {
27
+ "device": "cpu",
28
+ "float_dtype": null
29
+ }
30
+ }
31
+ ]
32
+ }
checkpoints/guarded_insert/policy_postprocessor_step_0_unnormalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49d75a0225e9cafd655e6ac4da582fd857f7a1ab1119977733e733a0c6b4e758
3
+ size 10844
checkpoints/guarded_insert/policy_preprocessor.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_preprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "rename_observations_processor",
6
+ "config": {
7
+ "rename_map": {}
8
+ }
9
+ },
10
+ {
11
+ "registry_name": "to_batch_processor",
12
+ "config": {}
13
+ },
14
+ {
15
+ "registry_name": "device_processor",
16
+ "config": {
17
+ "device": "cuda",
18
+ "float_dtype": null
19
+ }
20
+ },
21
+ {
22
+ "registry_name": "normalizer_processor",
23
+ "config": {
24
+ "eps": 1e-08,
25
+ "features": {
26
+ "observation.images.center_camera": {
27
+ "type": "VISUAL",
28
+ "shape": [
29
+ 3,
30
+ 256,
31
+ 288
32
+ ]
33
+ },
34
+ "observation.images.left_camera": {
35
+ "type": "VISUAL",
36
+ "shape": [
37
+ 3,
38
+ 256,
39
+ 288
40
+ ]
41
+ },
42
+ "observation.images.right_camera": {
43
+ "type": "VISUAL",
44
+ "shape": [
45
+ 3,
46
+ 256,
47
+ 288
48
+ ]
49
+ },
50
+ "observation.state": {
51
+ "type": "STATE",
52
+ "shape": [
53
+ 48
54
+ ]
55
+ },
56
+ "action": {
57
+ "type": "ACTION",
58
+ "shape": [
59
+ 19
60
+ ]
61
+ }
62
+ },
63
+ "norm_map": {
64
+ "VISUAL": "MEAN_STD",
65
+ "STATE": "MEAN_STD",
66
+ "ACTION": "MEAN_STD"
67
+ }
68
+ },
69
+ "state_file": "policy_preprocessor_step_3_normalizer_processor.safetensors"
70
+ }
71
+ ]
72
+ }
checkpoints/guarded_insert/policy_preprocessor_step_3_normalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49d75a0225e9cafd655e6ac4da582fd857f7a1ab1119977733e733a0c6b4e758
3
+ size 10844
checkpoints/guarded_insert/train_config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": {
3
+ "repo_id": "guarded_insert",
4
+ "root": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/act_stage_datasets/sc_stage_fixed_scene_curated_001_2026-05-05_00-48-03/datasets/guarded_insert",
5
+ "episodes": null,
6
+ "image_transforms": {
7
+ "enable": false,
8
+ "max_num_transforms": 3,
9
+ "random_order": false,
10
+ "tfs": {
11
+ "brightness": {
12
+ "weight": 1.0,
13
+ "type": "ColorJitter",
14
+ "kwargs": {
15
+ "brightness": [
16
+ 0.8,
17
+ 1.2
18
+ ]
19
+ }
20
+ },
21
+ "contrast": {
22
+ "weight": 1.0,
23
+ "type": "ColorJitter",
24
+ "kwargs": {
25
+ "contrast": [
26
+ 0.8,
27
+ 1.2
28
+ ]
29
+ }
30
+ },
31
+ "saturation": {
32
+ "weight": 1.0,
33
+ "type": "ColorJitter",
34
+ "kwargs": {
35
+ "saturation": [
36
+ 0.5,
37
+ 1.5
38
+ ]
39
+ }
40
+ },
41
+ "hue": {
42
+ "weight": 1.0,
43
+ "type": "ColorJitter",
44
+ "kwargs": {
45
+ "hue": [
46
+ -0.05,
47
+ 0.05
48
+ ]
49
+ }
50
+ },
51
+ "sharpness": {
52
+ "weight": 1.0,
53
+ "type": "SharpnessJitter",
54
+ "kwargs": {
55
+ "sharpness": [
56
+ 0.5,
57
+ 1.5
58
+ ]
59
+ }
60
+ },
61
+ "affine": {
62
+ "weight": 1.0,
63
+ "type": "RandomAffine",
64
+ "kwargs": {
65
+ "degrees": [
66
+ -5.0,
67
+ 5.0
68
+ ],
69
+ "translate": [
70
+ 0.05,
71
+ 0.05
72
+ ]
73
+ }
74
+ }
75
+ }
76
+ },
77
+ "revision": null,
78
+ "use_imagenet_stats": true,
79
+ "video_backend": "pyav",
80
+ "streaming": false
81
+ },
82
+ "env": null,
83
+ "policy": {
84
+ "type": "act",
85
+ "n_obs_steps": 1,
86
+ "input_features": {
87
+ "observation.images.center_camera": {
88
+ "type": "VISUAL",
89
+ "shape": [
90
+ 3,
91
+ 256,
92
+ 288
93
+ ]
94
+ },
95
+ "observation.images.left_camera": {
96
+ "type": "VISUAL",
97
+ "shape": [
98
+ 3,
99
+ 256,
100
+ 288
101
+ ]
102
+ },
103
+ "observation.images.right_camera": {
104
+ "type": "VISUAL",
105
+ "shape": [
106
+ 3,
107
+ 256,
108
+ 288
109
+ ]
110
+ },
111
+ "observation.state": {
112
+ "type": "STATE",
113
+ "shape": [
114
+ 48
115
+ ]
116
+ }
117
+ },
118
+ "output_features": {
119
+ "action": {
120
+ "type": "ACTION",
121
+ "shape": [
122
+ 19
123
+ ]
124
+ }
125
+ },
126
+ "device": "cuda",
127
+ "use_amp": false,
128
+ "use_peft": false,
129
+ "push_to_hub": false,
130
+ "repo_id": null,
131
+ "private": null,
132
+ "tags": null,
133
+ "license": null,
134
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
135
+ "chunk_size": 100,
136
+ "n_action_steps": 100,
137
+ "normalization_mapping": {
138
+ "VISUAL": "MEAN_STD",
139
+ "STATE": "MEAN_STD",
140
+ "ACTION": "MEAN_STD"
141
+ },
142
+ "vision_backbone": "resnet18",
143
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
144
+ "replace_final_stride_with_dilation": false,
145
+ "pre_norm": false,
146
+ "dim_model": 512,
147
+ "n_heads": 8,
148
+ "dim_feedforward": 3200,
149
+ "feedforward_activation": "relu",
150
+ "n_encoder_layers": 4,
151
+ "n_decoder_layers": 1,
152
+ "use_vae": true,
153
+ "latent_dim": 32,
154
+ "n_vae_encoder_layers": 4,
155
+ "temporal_ensemble_coeff": null,
156
+ "dropout": 0.1,
157
+ "kl_weight": 10.0,
158
+ "optimizer_lr": 1e-05,
159
+ "optimizer_weight_decay": 0.0001,
160
+ "optimizer_lr_backbone": 1e-05
161
+ },
162
+ "output_dir": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_guarded_insert/2026-05-06_00-46-05",
163
+ "job_name": "sc_stage_fixed_scene_curated_001_v1_guarded_insert_2026-05-06_00-46-05",
164
+ "resume": false,
165
+ "seed": 1000,
166
+ "num_workers": 2,
167
+ "batch_size": 8,
168
+ "steps": 10000,
169
+ "eval_freq": 1000000,
170
+ "log_freq": 100,
171
+ "tolerance_s": 0.0001,
172
+ "save_checkpoint": true,
173
+ "save_freq": 2000,
174
+ "use_policy_training_preset": true,
175
+ "optimizer": {
176
+ "type": "adamw",
177
+ "lr": 1e-05,
178
+ "weight_decay": 0.0001,
179
+ "grad_clip_norm": 10.0,
180
+ "betas": [
181
+ 0.9,
182
+ 0.999
183
+ ],
184
+ "eps": 1e-08
185
+ },
186
+ "scheduler": null,
187
+ "eval": {
188
+ "n_episodes": 50,
189
+ "batch_size": 50,
190
+ "use_async_envs": false
191
+ },
192
+ "wandb": {
193
+ "enable": false,
194
+ "disable_artifact": false,
195
+ "project": "lerobot",
196
+ "entity": null,
197
+ "notes": null,
198
+ "run_id": null,
199
+ "mode": null
200
+ },
201
+ "peft": null,
202
+ "use_rabc": false,
203
+ "rabc_progress_path": null,
204
+ "rabc_kappa": 0.01,
205
+ "rabc_epsilon": 1e-06,
206
+ "rabc_head_mode": "sparse",
207
+ "rename_map": {},
208
+ "checkpoint_path": null
209
+ }
checkpoints/retry_or_finish/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "act",
3
+ "n_obs_steps": 1,
4
+ "input_features": {
5
+ "observation.images.center_camera": {
6
+ "type": "VISUAL",
7
+ "shape": [
8
+ 3,
9
+ 256,
10
+ 288
11
+ ]
12
+ },
13
+ "observation.images.left_camera": {
14
+ "type": "VISUAL",
15
+ "shape": [
16
+ 3,
17
+ 256,
18
+ 288
19
+ ]
20
+ },
21
+ "observation.images.right_camera": {
22
+ "type": "VISUAL",
23
+ "shape": [
24
+ 3,
25
+ 256,
26
+ 288
27
+ ]
28
+ },
29
+ "observation.state": {
30
+ "type": "STATE",
31
+ "shape": [
32
+ 48
33
+ ]
34
+ }
35
+ },
36
+ "output_features": {
37
+ "action": {
38
+ "type": "ACTION",
39
+ "shape": [
40
+ 19
41
+ ]
42
+ }
43
+ },
44
+ "device": "cuda",
45
+ "use_amp": false,
46
+ "use_peft": false,
47
+ "push_to_hub": false,
48
+ "repo_id": null,
49
+ "private": null,
50
+ "tags": null,
51
+ "license": null,
52
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
53
+ "chunk_size": 100,
54
+ "n_action_steps": 100,
55
+ "normalization_mapping": {
56
+ "VISUAL": "MEAN_STD",
57
+ "STATE": "MEAN_STD",
58
+ "ACTION": "MEAN_STD"
59
+ },
60
+ "vision_backbone": "resnet18",
61
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
62
+ "replace_final_stride_with_dilation": false,
63
+ "pre_norm": false,
64
+ "dim_model": 512,
65
+ "n_heads": 8,
66
+ "dim_feedforward": 3200,
67
+ "feedforward_activation": "relu",
68
+ "n_encoder_layers": 4,
69
+ "n_decoder_layers": 1,
70
+ "use_vae": true,
71
+ "latent_dim": 32,
72
+ "n_vae_encoder_layers": 4,
73
+ "temporal_ensemble_coeff": null,
74
+ "dropout": 0.1,
75
+ "kl_weight": 10.0,
76
+ "optimizer_lr": 1e-05,
77
+ "optimizer_weight_decay": 0.0001,
78
+ "optimizer_lr_backbone": 1e-05
79
+ }
checkpoints/retry_or_finish/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b4217c592db5749575b8ee1aa55cf50f321b6fd1e8c469ef65efefb944e510d
3
+ size 206925068
checkpoints/retry_or_finish/policy_postprocessor.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_postprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "unnormalizer_processor",
6
+ "config": {
7
+ "eps": 1e-08,
8
+ "features": {
9
+ "action": {
10
+ "type": "ACTION",
11
+ "shape": [
12
+ 19
13
+ ]
14
+ }
15
+ },
16
+ "norm_map": {
17
+ "VISUAL": "MEAN_STD",
18
+ "STATE": "MEAN_STD",
19
+ "ACTION": "MEAN_STD"
20
+ }
21
+ },
22
+ "state_file": "policy_postprocessor_step_0_unnormalizer_processor.safetensors"
23
+ },
24
+ {
25
+ "registry_name": "device_processor",
26
+ "config": {
27
+ "device": "cpu",
28
+ "float_dtype": null
29
+ }
30
+ }
31
+ ]
32
+ }
checkpoints/retry_or_finish/policy_postprocessor_step_0_unnormalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7f94ca3d5b039226954d77de9d5e5f52564578c344bae69a98cf08025addbf5
3
+ size 10844
checkpoints/retry_or_finish/policy_preprocessor.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "policy_preprocessor",
3
+ "steps": [
4
+ {
5
+ "registry_name": "rename_observations_processor",
6
+ "config": {
7
+ "rename_map": {}
8
+ }
9
+ },
10
+ {
11
+ "registry_name": "to_batch_processor",
12
+ "config": {}
13
+ },
14
+ {
15
+ "registry_name": "device_processor",
16
+ "config": {
17
+ "device": "cuda",
18
+ "float_dtype": null
19
+ }
20
+ },
21
+ {
22
+ "registry_name": "normalizer_processor",
23
+ "config": {
24
+ "eps": 1e-08,
25
+ "features": {
26
+ "observation.images.center_camera": {
27
+ "type": "VISUAL",
28
+ "shape": [
29
+ 3,
30
+ 256,
31
+ 288
32
+ ]
33
+ },
34
+ "observation.images.left_camera": {
35
+ "type": "VISUAL",
36
+ "shape": [
37
+ 3,
38
+ 256,
39
+ 288
40
+ ]
41
+ },
42
+ "observation.images.right_camera": {
43
+ "type": "VISUAL",
44
+ "shape": [
45
+ 3,
46
+ 256,
47
+ 288
48
+ ]
49
+ },
50
+ "observation.state": {
51
+ "type": "STATE",
52
+ "shape": [
53
+ 48
54
+ ]
55
+ },
56
+ "action": {
57
+ "type": "ACTION",
58
+ "shape": [
59
+ 19
60
+ ]
61
+ }
62
+ },
63
+ "norm_map": {
64
+ "VISUAL": "MEAN_STD",
65
+ "STATE": "MEAN_STD",
66
+ "ACTION": "MEAN_STD"
67
+ }
68
+ },
69
+ "state_file": "policy_preprocessor_step_3_normalizer_processor.safetensors"
70
+ }
71
+ ]
72
+ }
checkpoints/retry_or_finish/policy_preprocessor_step_3_normalizer_processor.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7f94ca3d5b039226954d77de9d5e5f52564578c344bae69a98cf08025addbf5
3
+ size 10844
checkpoints/retry_or_finish/train_config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": {
3
+ "repo_id": "retry_or_finish",
4
+ "root": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/act_stage_datasets/sc_stage_fixed_scene_curated_001_2026-05-05_00-48-03/datasets/retry_or_finish",
5
+ "episodes": null,
6
+ "image_transforms": {
7
+ "enable": false,
8
+ "max_num_transforms": 3,
9
+ "random_order": false,
10
+ "tfs": {
11
+ "brightness": {
12
+ "weight": 1.0,
13
+ "type": "ColorJitter",
14
+ "kwargs": {
15
+ "brightness": [
16
+ 0.8,
17
+ 1.2
18
+ ]
19
+ }
20
+ },
21
+ "contrast": {
22
+ "weight": 1.0,
23
+ "type": "ColorJitter",
24
+ "kwargs": {
25
+ "contrast": [
26
+ 0.8,
27
+ 1.2
28
+ ]
29
+ }
30
+ },
31
+ "saturation": {
32
+ "weight": 1.0,
33
+ "type": "ColorJitter",
34
+ "kwargs": {
35
+ "saturation": [
36
+ 0.5,
37
+ 1.5
38
+ ]
39
+ }
40
+ },
41
+ "hue": {
42
+ "weight": 1.0,
43
+ "type": "ColorJitter",
44
+ "kwargs": {
45
+ "hue": [
46
+ -0.05,
47
+ 0.05
48
+ ]
49
+ }
50
+ },
51
+ "sharpness": {
52
+ "weight": 1.0,
53
+ "type": "SharpnessJitter",
54
+ "kwargs": {
55
+ "sharpness": [
56
+ 0.5,
57
+ 1.5
58
+ ]
59
+ }
60
+ },
61
+ "affine": {
62
+ "weight": 1.0,
63
+ "type": "RandomAffine",
64
+ "kwargs": {
65
+ "degrees": [
66
+ -5.0,
67
+ 5.0
68
+ ],
69
+ "translate": [
70
+ 0.05,
71
+ 0.05
72
+ ]
73
+ }
74
+ }
75
+ }
76
+ },
77
+ "revision": null,
78
+ "use_imagenet_stats": true,
79
+ "video_backend": "pyav",
80
+ "streaming": false
81
+ },
82
+ "env": null,
83
+ "policy": {
84
+ "type": "act",
85
+ "n_obs_steps": 1,
86
+ "input_features": {
87
+ "observation.images.center_camera": {
88
+ "type": "VISUAL",
89
+ "shape": [
90
+ 3,
91
+ 256,
92
+ 288
93
+ ]
94
+ },
95
+ "observation.images.left_camera": {
96
+ "type": "VISUAL",
97
+ "shape": [
98
+ 3,
99
+ 256,
100
+ 288
101
+ ]
102
+ },
103
+ "observation.images.right_camera": {
104
+ "type": "VISUAL",
105
+ "shape": [
106
+ 3,
107
+ 256,
108
+ 288
109
+ ]
110
+ },
111
+ "observation.state": {
112
+ "type": "STATE",
113
+ "shape": [
114
+ 48
115
+ ]
116
+ }
117
+ },
118
+ "output_features": {
119
+ "action": {
120
+ "type": "ACTION",
121
+ "shape": [
122
+ 19
123
+ ]
124
+ }
125
+ },
126
+ "device": "cuda",
127
+ "use_amp": false,
128
+ "use_peft": false,
129
+ "push_to_hub": false,
130
+ "repo_id": null,
131
+ "private": null,
132
+ "tags": null,
133
+ "license": null,
134
+ "pretrained_path": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_scripted_full_003_clean_plus_recovery_ft_control/2026-05-04_23-30-00/checkpoints/005000/pretrained_model",
135
+ "chunk_size": 100,
136
+ "n_action_steps": 100,
137
+ "normalization_mapping": {
138
+ "VISUAL": "MEAN_STD",
139
+ "STATE": "MEAN_STD",
140
+ "ACTION": "MEAN_STD"
141
+ },
142
+ "vision_backbone": "resnet18",
143
+ "pretrained_backbone_weights": "ResNet18_Weights.IMAGENET1K_V1",
144
+ "replace_final_stride_with_dilation": false,
145
+ "pre_norm": false,
146
+ "dim_model": 512,
147
+ "n_heads": 8,
148
+ "dim_feedforward": 3200,
149
+ "feedforward_activation": "relu",
150
+ "n_encoder_layers": 4,
151
+ "n_decoder_layers": 1,
152
+ "use_vae": true,
153
+ "latent_dim": 32,
154
+ "n_vae_encoder_layers": 4,
155
+ "temporal_ensemble_coeff": null,
156
+ "dropout": 0.1,
157
+ "kl_weight": 10.0,
158
+ "optimizer_lr": 1e-05,
159
+ "optimizer_weight_decay": 0.0001,
160
+ "optimizer_lr_backbone": 1e-05
161
+ },
162
+ "output_dir": "/home/starforge-sf95/Black-Projects/Project-Automaton/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_retry_or_finish/2026-05-06_00-51-10",
163
+ "job_name": "sc_stage_fixed_scene_curated_001_v1_retry_or_finish_2026-05-06_00-51-10",
164
+ "resume": false,
165
+ "seed": 1000,
166
+ "num_workers": 2,
167
+ "batch_size": 8,
168
+ "steps": 10000,
169
+ "eval_freq": 1000000,
170
+ "log_freq": 100,
171
+ "tolerance_s": 0.0001,
172
+ "save_checkpoint": true,
173
+ "save_freq": 2000,
174
+ "use_policy_training_preset": true,
175
+ "optimizer": {
176
+ "type": "adamw",
177
+ "lr": 1e-05,
178
+ "weight_decay": 0.0001,
179
+ "grad_clip_norm": 10.0,
180
+ "betas": [
181
+ 0.9,
182
+ 0.999
183
+ ],
184
+ "eps": 1e-08
185
+ },
186
+ "scheduler": null,
187
+ "eval": {
188
+ "n_episodes": 50,
189
+ "batch_size": 50,
190
+ "use_async_envs": false
191
+ },
192
+ "wandb": {
193
+ "enable": false,
194
+ "disable_artifact": false,
195
+ "project": "lerobot",
196
+ "entity": null,
197
+ "notes": null,
198
+ "run_id": null,
199
+ "mode": null
200
+ },
201
+ "peft": null,
202
+ "use_rabc": false,
203
+ "rabc_progress_path": null,
204
+ "rabc_kappa": 0.01,
205
+ "rabc_epsilon": 1e-06,
206
+ "rabc_head_mode": "sparse",
207
+ "rename_map": {},
208
+ "checkpoint_path": null
209
+ }
docs/technique.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Quantarune SC Insertion Technique
2
+
3
+ Oct 27, 2026 · @Shi Hao
4
+
5
+ A learned ACT policy brings an SC plug to the port mouth, and a short scripted wiggle-descent pushes it home, with ground truth off. On SC scene `sc_scripted_smoke_001_004` the frozen setting reached a full insertion (about 97.7 of 100) in 4 of 28 trials (14%); every other trial stopped about 13 mm short of the seat.
6
+
7
+ ## Task and constraints
8
+
9
+ A UR5e arm in Gazebo must insert the SC plug of a cable into a target port on a task board. The official AIC scoring engine grades each trial out of about 100: 1 point for a valid model, up to about 25 for duration, path efficiency and smoothness, and 75 for a full insertion.
10
+
11
+ - **Sensors the policy may use:** three wrist cameras (left, centre, right), a wrist force/torque sensor, joint states and the controller state.
12
+ - **Controller:** a Cartesian impedance controller that takes a target pose plus stiffness and damping per axis.
13
+ - **Hard rule:** ground truth is off in scored evaluation, so the true port pose is not available as TF. Every result below marked ground truth off ran with `ground_truth:=false`, which we checked in the launch log (no ground-truth TF relay) and in the bags (no port frames on `/tf`). Precisely: no ground-truth port pose is used for control, but termination reads the scorer's `/scoring/insertion_event`, pending a rules check.
14
+ - **Reference ceiling:** the toolkit's scripted `CheatCode`, which reads the true port pose, scores about 278 of 300 over three trials with ground truth on.
15
+
16
+ ## Pipeline
17
+
18
+ One policy class, `RunACTStagedScriptedInsert`, runs four learned phases and then one scripted phase. It subclasses `RunACTStaged`, which is a four-state FSM wrapped around per-phase ACT checkpoints.
19
+
20
+ 1. **APPROACH (learned):** the approach ACT model moves the plug from home towards the board.
21
+ 2. **ALIGN (learned):** the align ACT model centres the plug over the port. The FSM moves on when the ACT target is stable, the XY error is within 15 mm, the angle error is within 0.12 rad, and both have held for 0.75 s.
22
+ 3. **GUARDED_INSERT (wrapper + learned orientation):** the wrapper pushes the plug along an insert direction estimated once from the ACT pose. It takes only the orientation from the guarded-insert model. This phase pulls the plug onto the port axis.
23
+ 4. **Hand-off:** the wrapper gives up after a fixed window (5 s here) without an insertion event. At that moment the plug sits at the port lip, about 13 mm above the seat.
24
+ 5. **Scripted finish:** a stiff, slow vertical descent with a small circular wiggle, from the hand-off pose (next sections).
25
+
26
+ The wrapper also has a RETRY_OR_FINISH phase: it backs out 10 mm and re-aligns when progress stalls. It triggers when the push gains less than 1.5 mm in the window. In every final-configuration trial the push gained more than that, so the hand-off came at the end of the first window and no retry ran.
27
+
28
+ ## Learned stages
29
+
30
+ Each phase has its own ACT checkpoint, trained by behaviour cloning on scripted `CheatCode` demonstrations, split by the teacher's own stage labels. All four come from the team's own training chain.
31
+
32
+ | Phase | Checkpoint (under `quantarune_training/outputs/`) | Training data | Episodes | Frames (20 fps) |
33
+ | --- | --- | --- | --- | --- |
34
+ | Approach | `sc_stage_fixed_scene_curated_001_v1_approach`, step 10000 | `act_stage_datasets/sc_stage_fixed_scene_curated_001_…/datasets/approach` | 37 | 4,595 |
35
+ | Align | `…_v1_align`, step 10000 | `…/datasets/align` | 37 | 4,697 |
36
+ | Guarded insert | `…_v1_guarded_insert`, step 10000 | `…/datasets/guarded_insert` | 37 | 2,581 |
37
+ | Retry or finish | `…_v1_retry_or_finish`, step 10000 | `…/datasets/retry_or_finish` | 36 | 6,638 |
38
+
39
+ - **Model:** LeRobot ACT, 48-dim state, 19-dim action, chunk size 100, pose command mode. Each was fine-tuned for 10,000 steps.
40
+ - **Lineage:** `sc_scripted_full_003_plus_perturb_micro_curated_long` (step 10000) → `sc_scripted_full_003_clean_plus_recovery_ft_control` (step 5000) → the four stage models.
41
+ - **Wrapper settings:** guarded step 5.25 mm per 0.25 s tick (0.06 m/s × 0.25 s × 0.35), impedance 85 N/m per axis, damping 75. The force ramp runs from 12 N to 18 N, with a hard stop at 19 N.
42
+ - **Recipe overrides:** guarded window 5 s (default 1.5 s), progress threshold 1.5 mm (default), 3 retries. A 5 cm progress threshold, copied from a demo recipe, caused random retries and was dropped.
43
+ - **Privileged target:** the wrapper's ground-truth port target (`AIC_ACT_STAGED_PRIVILEGED_TERMINAL_TARGET`) is off by default and stayed off.
44
+
45
+ ## Scripted finish
46
+
47
+ The finish reads no port pose. It holds the hand-off orientation, moves the target straight down in `base_link`, and circles the target in XY so a plug resting on the lip can find the opening.
48
+
49
+ | Parameter | Value | Setting |
50
+ | --- | --- | --- |
51
+ | Descent speed | 4 mm/s | `AIC_SCRIPTED_INSERT_SPEED_MPS` |
52
+ | Descent target | 25 mm below the hand-off pose | `AIC_SCRIPTED_INSERT_DEPTH_M` |
53
+ | Stiffness (x, y, z / rotations) | 400 N/m / 85 | `AIC_SCRIPTED_INSERT_STIFFNESS` |
54
+ | Wiggle | circle at 1 Hz, radius 0.5 mm, +0.25 mm per 1 s without 0.5 mm of descent, max 2.5 mm | `AIC_SCRIPTED_INSERT_WIGGLE_*` |
55
+ | Control period | 0.05 s | `AIC_SCRIPTED_INSERT_PERIOD_S` |
56
+ | Force stop | 15 N (compensated force magnitude) | `AIC_SCRIPTED_INSERT_STOP_FORCE_N` |
57
+ | Time limit | 15 s | `AIC_SCRIPTED_INSERT_TIME_S` |
58
+
59
+ The finish ends on the first of three events: an insertion event, the force stop or the time limit. It always returns success to the engine, and the engine scores the actual plug state. Only the finish runs at 400 N/m. The learned phases keep 85 N/m, because their ACT models were trained at that stiffness; a global 400 to 1000 N/m made the approach drift 10 to 16 cm off.
60
+
61
+ ## Results
62
+
63
+ Only the final configuration inserts with ground truth off, all on SC scene 004. The frozen baseline setting (400 N/m, 1 Hz, 2.5 mm wiggle) inserted in 4 of 28 trials (14%); 7 of 37 pools several settings and is not one configuration's rate. Every row except the CheatCode reference ran on that scene with the same approach and align checkpoints. The reference ran on the toolkit's three-trial sample configuration.
64
+
65
+ | Configuration | Ground truth | Trials | Full insertions | Score per trial | Where the plug ended |
66
+ | --- | --- | --- | --- | --- | --- |
67
+ | `CheatCode` reference (true port pose) | on | 3 | 3 | ~93 | seated |
68
+ | `RunACTStaged`, original recipe | on | 2 | 1 | 96.7, 64.1 | seated; 12.5 mm short |
69
+ | `RunACTStaged`, original or swapped insert checkpoints, 5 s and 15 s windows | off | 7 | 0 | 58.9–68.1 | 6.5–13.4 mm short, 0.3–1.7 mm off-axis |
70
+ | `RunACTStaged`, global stiffness 400 or 1000 N/m | off | 2 | 0 | 31.8, 21.1 | 10–16 cm off |
71
+ | `RunACTStagedV2`, target anchored at stage start | off | 3 | 0 | 48.2–48.6 | 3–12 mm short, 13 mm off-axis |
72
+ | `RunACTStagedV2`, lead from current pose, 5 cm threshold | off | 3 | 0 | 35.5–48.5 | 2 of 3 retried and ended 83 mm high |
73
+ | `RunACTStagedV2`, lead from current pose, 1.5 mm threshold | off | 3 | 0 | 47.9–62.5 | 13–14 mm short, 4.7–5.7 mm off-axis |
74
+ | Scripted finish, early hand-off (start of guarded insert) | off | 3 | 0 | 43.1–43.9 | 22–27 mm short, 10–12 mm off-axis |
75
+ | Scripted finish, late hand-off, 85 N/m | off | 3 | 0 | 60.0 | lip; 0.0 mm descent |
76
+ | **Scripted finish, late hand-off, 400–800 N/m (final)** | off | 37 | **7** | 96.9–98.0 full; ~60 otherwise | seated, or lip with 0.0 mm descent |
77
+
78
+ The final configuration's 37 trials break down as follows. The settings made no clear difference.
79
+
80
+ | Batch (all on 27 Oct) | Setting | Trials | Full insertions |
81
+ | --- | --- | --- | --- |
82
+ | First test | 400 N/m, wiggle max 2.5 mm, 1 Hz | 3 | 1 |
83
+ | Recording takes, night | same | 7 | 1 |
84
+ | Tuning a0 | same | 3 | 0 |
85
+ | Tuning a1 | 800 N/m, 20 N stop | 3 | 1 |
86
+ | Tuning a2 | 400 N/m, wiggle max 1 mm, 2 Hz | 3 | 1 |
87
+ | Tuning a3 | 800 N/m and the small 2 Hz wiggle | 3 | 1 |
88
+ | Recording takes, morning | 400 N/m, wiggle max 2.5 mm, 1 Hz | 15 | 2 |
89
+
90
+ ## Failure analysis
91
+
92
+ Every failed trial stops at the same place: about 13 mm above the seat, well aligned, with low force. We measured this from `/scoring/tf` in each trial's bag. The plug tip (`cable_1/sc_tip_link`) is expressed in the port frame (`task_board/sc_port_0/sc_port_base_link`), relative to the tip's final pose in the seated 96.7 run.
93
+
94
+ | Measure at the stall | Value |
95
+ | --- | --- |
96
+ | Height above the seated position | 12.4–13.4 mm (the port entrance is 16 mm above the seat) |
97
+ | Sideways error (original `RunACTStaged`) | 0.3–1.7 mm |
98
+ | Tilt against the seated run | under 0.3° |
99
+ | Peak contact force during the push | under 4 N |
100
+
101
+ - **Ruled out as the sole cause:** tilt, sideways error (the 64.1 ground-truth run stalled at 0.3 mm off-axis) and push force (V2 pushed harder, got no deeper and drifted 13 mm sideways).
102
+ - **What the 96.7 run did differently:** it reached the same 12.8 mm point at 10 s, backed out slightly in a retry, then sank at about 1.3 mm/s for 8 s until seated. The 64.1 run reached 12.4 mm at 10 s, and its episode ended a second later.
103
+ - **Scripted-finish failures are all or nothing:** a success descends 8.9–12 mm within seconds while the wiggle is still 0.5–1.0 mm. A failure moves 0.0 mm for the full 15 s, even at 800 N/m with a 20 N stop, and never trips the force stop.
104
+ - **Two open explanations:** either the plug is jammed and the force reading misses the load (the sensor is tared at an unknown moment), or the finish's pose commands are not reaching the controller. Neither is confirmed yet.
105
+
106
+ ## Questions for the reviewer
107
+
108
+ These are the points we are least sure of, roughly in order of risk.
109
+
110
+ 1. **Legality of the stop signal.** The wrapper and the scripted finish stop when they see the scorer's insertion event. Is that topic available to a policy in the official evaluation, and is reacting to it allowed?
111
+ 2. **Stiff wiggle or compliant search?** The finish holds 400 N/m in XY and circles blindly. Would low XY stiffness during descent let the port chamfer centre the plug better? Would a force-guided spiral search work better?
112
+ 3. **Jam or lost commands?** Failed finishes show 0.0 mm of descent and no force stop. What F/T or controller-state signal would tell a wedged plug from a command that never applied?
113
+ 4. **What sits 13 mm above the seat?** Every failure stops there, 3 mm inside a 16 mm entrance. Is that a known feature of the SC port, such as a latch or a collar, with its own force threshold?
114
+ 5. **Hand-off on a timer.** Control hands over after a fixed 5 s window, not on a measured event. Should it hand off on a force rise or a progress stall instead?
115
+ 6. **Insert direction.** The wrapper fixes its push direction once, from the learned pose at the end of align. Should the final push follow a perceived port axis instead?
116
+ 7. **Statistics.** The frozen baseline is 4 of 28 (14%); the pooled 7 of 37 (19%, Wilson 95% interval 9.5–34.2%) mixes settings. Three trials per setting cannot separate the tuning settings.
117
+ 8. **Generalisation.** The stage models saw 36–37 episodes of one scene family, and we tested only scene 004. How much should we trust this on other board poses?
118
+
119
+ ## Next steps
120
+
121
+ The next decision is whether the scripted finish can become reliable, or whether a learned corrector must replace its blind wiggle. A scripted finish near 70% across about ten SC scenes would be kept, because it is simpler. Near 20%, the corrector is worth training.
122
+
123
+ 1. **Instrument the finish.** Log the TCP pose, whether `move_robot` accepted each command, and the untared force on every tick. Three trials then show whether failures are jams or lost commands.
124
+ 2. **Add a retry to the finish.** After 3 s without descent, lift 10 mm, reset the wiggle and descend again, up to 3 times. This copies what the 96.7 run did.
125
+ 3. **Screen more scenes.** Run scenes `sc_scripted_smoke_001_001` to `020`, two trials each, to label each scene easy or hard.
126
+ 4. **Train the InsertionNet-style corrector.** The data is collected: 2,322 samples from 95 trials (1,347 SC, 975 SFP). Each holds three wrist images, the tared wrench, and the 6-DoF move back to the seated pose, labelled with ground truth during collection. The model is a small CNN shared across the three cameras, plus a wrench MLP, trained with MSE for 80 epochs, with validation split by trial. At run time, `RunACTInsertionNet` replaces the guarded insert after align and applies half of each clipped prediction.
127
+ 5. **SFP.** Not attempted with this technique. The SFP approach model stops 4–6 cm short, and nobody has checked whether the SFP port axis is vertical in `base_link`.
128
+
129
+ ## Sources
130
+
131
+ All paths are on the team workstation, under `Black-Projects/Project-Automaton/Santa_Maria/`.
132
+
133
+ | What | Path |
134
+ | --- | --- |
135
+ | Final policy | `code/aic-quantarune/aic_example_policies/aic_example_policies/ros/RunACTStagedScriptedInsert.py` |
136
+ | Wrapper and its parents | `…/ros/RunACTStaged.py`, `RunACTCompetitor.py`, `RunACT.py` (insertion-event subscription on `/scoring/insertion_event`) |
137
+ | Abandoned variant | `…/ros/RunACTStagedV2.py` |
138
+ | Stage checkpoints | `code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_*` |
139
+ | Scene | `code/aic-quantarune-isaac-training/quantarune_data/outputs/fixed_scene_batches/sc_scripted_smoke_001/configs/sc_scripted_smoke_001_004.yaml` |
140
+ | Trial runs (scores, configs, bags) | `code/aic-quantarune/aic_eval_runs/` — `stitch-*`, `video-scripted-insert-*`, `gui-sc-staged-retry-004-20261026_164224` (96.7 reference) |
141
+ | InsertionNet code and data | `code/aic-quantarune/insertion_net/`, `data/insertionnet/collect_20261026/` |
142
+ | Videos of full insertions | `~/Videos/RunACTStaged + scripted insert [SC 004, gt-off] 20261027_012459.mp4`, `…_071711.mp4`, `…_072823.mp4` |
policy/aic_example_policies/__init__.py ADDED
File without changes
policy/aic_example_policies/ros/RunACT.py ADDED
@@ -0,0 +1,2027 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2026 Intrinsic Innovation LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ import os
18
+
19
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
20
+
21
+ import time
22
+ import json
23
+ import re
24
+ import torch
25
+ import numpy as np
26
+ import cv2
27
+ import draccus
28
+ from dataclasses import dataclass, fields
29
+ from pathlib import Path
30
+ from typing import Callable, Dict, Any, List
31
+ from rclpy.node import Node
32
+ from geometry_msgs.msg import Pose, Point, Quaternion, Twist, Vector3
33
+ from tf2_msgs.msg import TFMessage
34
+ from std_msgs.msg import String
35
+
36
+ from aic_model.policy import (
37
+ GetObservationCallback,
38
+ MoveRobotCallback,
39
+ Policy,
40
+ SendFeedbackCallback,
41
+ )
42
+ from aic_model_interfaces.msg import Observation
43
+ from aic_task_interfaces.msg import Task
44
+
45
+ from aic_control_interfaces.msg import (
46
+ MotionUpdate,
47
+ TrajectoryGenerationMode,
48
+ )
49
+ from geometry_msgs.msg import Wrench
50
+
51
+ # LeRobot & Safetensors
52
+ from lerobot.policies.act.modeling_act import ACTPolicy
53
+ from lerobot.policies.act.configuration_act import ACTConfig
54
+ from safetensors.torch import load_file
55
+ from huggingface_hub import snapshot_download
56
+
57
+ from .canonical_episode_writer import (
58
+ CanonicalEpisodeWriter,
59
+ build_episode_id,
60
+ utc_now_iso,
61
+ )
62
+ from .vision_target_features import CenterPortFeatureExtractor
63
+
64
+
65
+ CABLE_TYPE_TO_ID = {
66
+ "unknown": 0,
67
+ "sfp_sc": 1,
68
+ }
69
+
70
+ PLUG_TYPE_TO_ID = {
71
+ "unknown": 0,
72
+ "sc": 1,
73
+ "sfp": 2,
74
+ "lc": 3,
75
+ }
76
+
77
+ PORT_TYPE_TO_ID = {
78
+ "unknown": 0,
79
+ "sc": 1,
80
+ "sfp": 2,
81
+ }
82
+
83
+ MODULE_NAME_TO_ID = {
84
+ "unknown": 0,
85
+ "nic_card_mount_0": 1,
86
+ "nic_card_mount_1": 2,
87
+ "nic_card_mount_2": 3,
88
+ "nic_card_mount_3": 4,
89
+ "nic_card_mount_4": 5,
90
+ "sc_port_0": 6,
91
+ "sc_port_1": 7,
92
+ }
93
+
94
+ PORT_NAME_TO_ID = {
95
+ "unknown": 0,
96
+ "sfp_port_0": 1,
97
+ "sfp_port_1": 2,
98
+ "sc_port_base": 3,
99
+ }
100
+
101
+ DEFAULT_48D_STATE_FEATURE_NAMES = [
102
+ "tcp_pose.position.x",
103
+ "tcp_pose.position.y",
104
+ "tcp_pose.position.z",
105
+ "tcp_pose.orientation.x",
106
+ "tcp_pose.orientation.y",
107
+ "tcp_pose.orientation.z",
108
+ "tcp_pose.orientation.w",
109
+ "tcp_velocity.linear.x",
110
+ "tcp_velocity.linear.y",
111
+ "tcp_velocity.linear.z",
112
+ "tcp_velocity.angular.x",
113
+ "tcp_velocity.angular.y",
114
+ "tcp_velocity.angular.z",
115
+ "tcp_error.x",
116
+ "tcp_error.y",
117
+ "tcp_error.z",
118
+ "tcp_error.rx",
119
+ "tcp_error.ry",
120
+ "tcp_error.rz",
121
+ "joint_positions.0",
122
+ "joint_positions.1",
123
+ "joint_positions.2",
124
+ "joint_positions.3",
125
+ "joint_positions.4",
126
+ "joint_positions.5",
127
+ "joint_positions.6",
128
+ "joint_velocity.0",
129
+ "joint_velocity.1",
130
+ "joint_velocity.2",
131
+ "joint_velocity.3",
132
+ "joint_velocity.4",
133
+ "joint_velocity.5",
134
+ "joint_velocity.6",
135
+ "wrench.force.x",
136
+ "wrench.force.y",
137
+ "wrench.force.z",
138
+ "wrench.torque.x",
139
+ "wrench.torque.y",
140
+ "wrench.torque.z",
141
+ "task.target_valid",
142
+ "task.cable_type_id",
143
+ "task.plug_type_id",
144
+ "task.port_type_id",
145
+ "task.target_module_id",
146
+ "task.target_port_id",
147
+ "task.target_module_index",
148
+ "task.target_port_index",
149
+ "task.time_limit",
150
+ ]
151
+
152
+
153
+ def _env_bool(name: str, default: bool = False) -> bool:
154
+ value = os.environ.get(name)
155
+ if value is None:
156
+ return default
157
+ return value.strip().lower() in {"1", "true", "yes", "on"}
158
+
159
+
160
+ def _env_float(name: str, default: float) -> float:
161
+ value = os.environ.get(name)
162
+ if value is None:
163
+ return default
164
+ try:
165
+ return float(value)
166
+ except ValueError:
167
+ return default
168
+
169
+
170
+ def _extract_suffix_index(name: str) -> float:
171
+ match = re.search(r"(\d+)$", name or "")
172
+ return float(int(match.group(1))) if match else -1.0
173
+
174
+
175
+ def _encode_task_numeric(task_msg: Task | None) -> dict[str, float]:
176
+ if task_msg is None:
177
+ return {
178
+ "task.target_valid": 0.0,
179
+ "task.cable_type_id": 0.0,
180
+ "task.plug_type_id": 0.0,
181
+ "task.port_type_id": 0.0,
182
+ "task.target_module_id": 0.0,
183
+ "task.target_port_id": 0.0,
184
+ "task.target_module_index": -1.0,
185
+ "task.target_port_index": -1.0,
186
+ "task.time_limit": 0.0,
187
+ }
188
+
189
+ return {
190
+ "task.target_valid": 1.0,
191
+ "task.cable_type_id": float(CABLE_TYPE_TO_ID.get(task_msg.cable_type, 0)),
192
+ "task.plug_type_id": float(PLUG_TYPE_TO_ID.get(task_msg.plug_type, 0)),
193
+ "task.port_type_id": float(PORT_TYPE_TO_ID.get(task_msg.port_type, 0)),
194
+ "task.target_module_id": float(
195
+ MODULE_NAME_TO_ID.get(task_msg.target_module_name, 0)
196
+ ),
197
+ "task.target_port_id": float(PORT_NAME_TO_ID.get(task_msg.port_name, 0)),
198
+ "task.target_module_index": _extract_suffix_index(task_msg.target_module_name),
199
+ "task.target_port_index": _extract_suffix_index(task_msg.port_name),
200
+ "task.time_limit": float(task_msg.time_limit),
201
+ }
202
+
203
+
204
+ @dataclass
205
+ class LoadedACTPolicyBundle:
206
+ route_key: str
207
+ policy_path: Path
208
+ checkpoint_name: str
209
+ policy: ACTPolicy
210
+ img_stats: dict[str, dict[str, torch.Tensor]]
211
+ state_mean: torch.Tensor
212
+ state_std: torch.Tensor
213
+ action_mean: torch.Tensor
214
+ action_std: torch.Tensor
215
+ state_dim: int
216
+ action_dim: int
217
+
218
+
219
+ class RunACT(Policy):
220
+ def __init__(self, parent_node: Node):
221
+ super().__init__(parent_node)
222
+ default_device = "cuda" if torch.cuda.is_available() else "cpu"
223
+ self.device = torch.device(os.environ.get("AIC_ACT_DEVICE", default_device))
224
+ self.log_every_n_steps = int(os.environ.get("AIC_ACT_LOG_EVERY_STEPS", "5"))
225
+ self.stats_eps = 1e-6
226
+ self._command_mode_preference = os.environ.get("AIC_ACT_COMMAND_MODE", "auto")
227
+ self.command_mode = self._command_mode_preference
228
+ self._policy_bundles: dict[str, LoadedACTPolicyBundle] = {}
229
+ self._active_policy_route = "default"
230
+
231
+ # -------------------------------------------------------------------------
232
+ # 1. Configuration & Weights Loading
233
+ # -------------------------------------------------------------------------
234
+ repo_id = os.environ.get("AIC_ACT_HF_REPO", "grkw/aic_act_policy")
235
+ policy_specs = self._resolve_policy_specs(repo_id)
236
+ for route_key, policy_path in policy_specs.items():
237
+ self._policy_bundles[route_key] = self._load_policy_bundle(
238
+ route_key, policy_path
239
+ )
240
+ self._validate_loaded_policy_bundles()
241
+ startup_route = (
242
+ "default"
243
+ if "default" in self._policy_bundles
244
+ else next(iter(self._policy_bundles))
245
+ )
246
+ self._activate_policy_bundle(startup_route, reason="startup")
247
+
248
+ # Config
249
+ self.image_scaling = 0.25 # Must match AICRobotAICControllerConfig
250
+ self.state_feature_names = list(DEFAULT_48D_STATE_FEATURE_NAMES)
251
+ self.cv_stale_threshold_ms = float(
252
+ os.environ.get("AIC_INSERTION_CV_STALE_THRESHOLD_MS", "250.0")
253
+ )
254
+ self.robot_state_stale_threshold_ms = float(
255
+ os.environ.get("AIC_INSERTION_ROBOT_STATE_STALE_THRESHOLD_MS", "250.0")
256
+ )
257
+ self.force_stale_threshold_ms = float(
258
+ os.environ.get("AIC_INSERTION_FORCE_STALE_THRESHOLD_MS", "250.0")
259
+ )
260
+ self._cv_extractor = CenterPortFeatureExtractor()
261
+ self._active_observation_msg: Observation | None = None
262
+ self._active_task: Task | None = None
263
+ self._active_move_robot: MoveRobotCallback | None = None
264
+ self._last_policy_observation: dict[str, Any] | None = None
265
+ self._latest_cv_observation: dict[str, Any] | None = None
266
+ self._previous_action_record: dict[str, Any] | None = None
267
+ self._episode_writer: CanonicalEpisodeWriter | None = None
268
+ self._episode_action_id = 0
269
+ self._episode_start_time_s: float | None = None
270
+ self._episode_last_action_result: dict[str, Any] | None = None
271
+ self._episode_last_wrapper_output: dict[str, Any] | None = None
272
+ self._episode_run_name = os.environ.get("AIC_RUN_NAME", "manual-run")
273
+ self._episode_source = os.environ.get(
274
+ "AIC_INSERTION_SOURCE", "wrapper_runtime"
275
+ )
276
+ self._episode_environment = os.environ.get(
277
+ "AIC_INSERTION_ENVIRONMENT", "sim"
278
+ )
279
+ self._episode_robot_type = os.environ.get(
280
+ "AIC_INSERTION_ROBOT_TYPE", "ur5e_hande"
281
+ )
282
+ self._episode_connector_type = os.environ.get(
283
+ "AIC_INSERTION_CONNECTOR_TYPE", "aic_model_action_server"
284
+ )
285
+ self._episode_root = self._resolve_episode_root()
286
+ self._runtime_geometry_jsonl_path = (
287
+ os.environ.get("AIC_ACT_RUNTIME_GEOMETRY_JSONL")
288
+ or os.environ.get("AIC_RUNTIME_GEOMETRY_JSONL")
289
+ or os.environ.get("AIC_CHEATCODE_RUNTIME_GEOMETRY_JSONL")
290
+ or ""
291
+ ).strip()
292
+ self.generic_scoring_tf_diagnostics_enabled = (
293
+ _env_bool("AIC_ACT_ENABLE_SCORING_TF_DIAGNOSTICS", False)
294
+ or _env_bool("AIC_ACT48_ENABLE_SCORING_TF_DIAGNOSTICS", False)
295
+ or _env_bool("AIC_ACT_STAGED_ENABLE_SCORING_TF_DIAGNOSTICS", False)
296
+ or bool(self._runtime_geometry_jsonl_path)
297
+ )
298
+ self._generic_scoring_tf_positions: dict[str, np.ndarray] = {}
299
+ self._generic_scoring_tf_raw_frames: dict[str, str] = {}
300
+ self._generic_last_plug_port_geometry: dict[str, object] = {}
301
+ self._generic_best_plug_port_distance_m: float | None = None
302
+ self._generic_best_plug_port_geometry: dict[str, object] = {}
303
+ self._runtime_geometry_seq = 0
304
+ self._insertion_event_seen = False
305
+ self._last_insertion_event = ""
306
+ self._insertion_events: list[str] = []
307
+ self._runtime_geometry_label_max_translation_m = _env_float(
308
+ "AIC_ACT_RUNTIME_GEOMETRY_LABEL_MAX_TRANSLATION_M", 0.006
309
+ )
310
+ self._runtime_geometry_force_safe_n = _env_float(
311
+ "AIC_ACT_RUNTIME_GEOMETRY_FORCE_SAFE_N", 20.0
312
+ )
313
+ self._runtime_geometry_lateral_force_safe_n = _env_float(
314
+ "AIC_ACT_RUNTIME_GEOMETRY_LATERAL_FORCE_SAFE_N", 7.0
315
+ )
316
+ self._generic_scoring_tf_sub = None
317
+ if self.generic_scoring_tf_diagnostics_enabled:
318
+ self._generic_scoring_tf_sub = self._parent_node.create_subscription(
319
+ TFMessage, "/scoring/tf", self._generic_scoring_tf_callback, 10
320
+ )
321
+ self._insertion_event_sub = self._parent_node.create_subscription(
322
+ String, "/scoring/insertion_event", self._insertion_event_callback, 10
323
+ )
324
+
325
+ self.get_logger().info(
326
+ "Normalization statistics loaded successfully. "
327
+ f"state_dim={self.state_dim} action_dim={self.action_dim} "
328
+ f"command_mode={self.command_mode} "
329
+ f"generic_scoring_tf_diagnostics={self.generic_scoring_tf_diagnostics_enabled} "
330
+ f"runtime_geometry_jsonl={self._runtime_geometry_jsonl_path or '<disabled>'}"
331
+ )
332
+
333
+ def _insertion_event_callback(self, msg: String) -> None:
334
+ self._insertion_event_seen = True
335
+ self._last_insertion_event = msg.data
336
+ self._insertion_events.append(msg.data)
337
+
338
+ @staticmethod
339
+ def _checkpoint_name_from_path(policy_path: Path) -> str:
340
+ return (
341
+ policy_path.parent.name
342
+ if policy_path.name == "pretrained_model"
343
+ else policy_path.name
344
+ )
345
+
346
+ def _resolve_policy_specs(self, repo_id: str) -> dict[str, Path]:
347
+ policy_specs: dict[str, Path] = {}
348
+ default_policy_path = (
349
+ os.environ.get("AIC_ACT_POLICY_PATH_DEFAULT")
350
+ or os.environ.get("AIC_ACT_POLICY_PATH")
351
+ )
352
+ if default_policy_path:
353
+ policy_specs["default"] = Path(default_policy_path).expanduser().resolve()
354
+
355
+ prefix = "AIC_ACT_POLICY_PATH_"
356
+ for env_key, route_policy_path in sorted(os.environ.items()):
357
+ if not env_key.startswith(prefix):
358
+ continue
359
+ suffix = env_key[len(prefix) :]
360
+ if not suffix or suffix == "DEFAULT":
361
+ continue
362
+ route_key = suffix.strip().lower()
363
+ if not route_key:
364
+ continue
365
+ policy_specs[route_key] = Path(route_policy_path).expanduser().resolve()
366
+
367
+ if policy_specs:
368
+ return policy_specs
369
+
370
+ policy_path = Path(
371
+ snapshot_download(
372
+ repo_id=repo_id,
373
+ allow_patterns=["config.json", "model.safetensors", "*.safetensors"],
374
+ )
375
+ )
376
+ self.get_logger().info(f"Loading ACT policy from HF repo: {repo_id}")
377
+ return {"default": policy_path}
378
+
379
+ def _resolve_bundle_command_mode(self, action_dim: int) -> str:
380
+ if self._command_mode_preference == "auto":
381
+ return "pose" if action_dim >= 13 else "twist"
382
+ return self._command_mode_preference
383
+
384
+ def _load_policy_bundle(
385
+ self, route_key: str, policy_path: Path
386
+ ) -> LoadedACTPolicyBundle:
387
+ if not policy_path.exists():
388
+ raise FileNotFoundError(f"ACT policy path not found: {policy_path}")
389
+
390
+ self.get_logger().info(
391
+ f"Loading ACT policy bundle route={route_key} from {policy_path}"
392
+ )
393
+
394
+ with open(policy_path / "config.json", "r") as f:
395
+ config_dict = json.load(f)
396
+ valid_config_keys = {field.name for field in fields(ACTConfig)}
397
+ config_dict = {
398
+ key: value for key, value in config_dict.items() if key in valid_config_keys
399
+ }
400
+ config_dict["pretrained_backbone_weights"] = None
401
+ config_dict["device"] = str(self.device)
402
+ config = draccus.decode(ACTConfig, config_dict)
403
+
404
+ policy = ACTPolicy(config)
405
+ load_result = policy.load_state_dict(
406
+ load_file(policy_path / "model.safetensors"), strict=False
407
+ )
408
+ policy.eval()
409
+ policy.to(self.device)
410
+
411
+ if load_result.missing_keys:
412
+ self.get_logger().warning(
413
+ f"ACT checkpoint route={route_key} loaded with missing keys: "
414
+ + ", ".join(load_result.missing_keys)
415
+ )
416
+ if load_result.unexpected_keys:
417
+ self.get_logger().warning(
418
+ f"ACT checkpoint route={route_key} loaded with unexpected keys: "
419
+ + ", ".join(load_result.unexpected_keys)
420
+ )
421
+
422
+ policy.normalize_inputs = torch.nn.Identity()
423
+ policy.unnormalize_outputs = torch.nn.Identity()
424
+
425
+ stats = load_file(
426
+ policy_path / "policy_preprocessor_step_3_normalizer_processor.safetensors"
427
+ )
428
+
429
+ def get_stat(key, shape, clamp_min: float | None = None):
430
+ value = stats[key].to(self.device).view(*shape)
431
+ if clamp_min is not None:
432
+ small_mask = value.abs() < clamp_min
433
+ small_count = int(small_mask.sum().item())
434
+ if small_count > 0:
435
+ self.get_logger().warning(
436
+ f"Clamping {small_count} near-zero entries in {key} "
437
+ f"for route={route_key} to {clamp_min}"
438
+ )
439
+ value = value.clone()
440
+ value[small_mask] = clamp_min
441
+ return value
442
+
443
+ img_stats = {
444
+ "left": {
445
+ "mean": get_stat("observation.images.left_camera.mean", (1, 3, 1, 1)),
446
+ "std": get_stat(
447
+ "observation.images.left_camera.std",
448
+ (1, 3, 1, 1),
449
+ clamp_min=self.stats_eps,
450
+ ),
451
+ },
452
+ "center": {
453
+ "mean": get_stat("observation.images.center_camera.mean", (1, 3, 1, 1)),
454
+ "std": get_stat(
455
+ "observation.images.center_camera.std",
456
+ (1, 3, 1, 1),
457
+ clamp_min=self.stats_eps,
458
+ ),
459
+ },
460
+ "right": {
461
+ "mean": get_stat("observation.images.right_camera.mean", (1, 3, 1, 1)),
462
+ "std": get_stat(
463
+ "observation.images.right_camera.std",
464
+ (1, 3, 1, 1),
465
+ clamp_min=self.stats_eps,
466
+ ),
467
+ },
468
+ }
469
+ state_mean = get_stat("observation.state.mean", (1, -1))
470
+ state_std = get_stat(
471
+ "observation.state.std", (1, -1), clamp_min=self.stats_eps
472
+ )
473
+ action_mean = get_stat("action.mean", (1, -1))
474
+ action_std = get_stat("action.std", (1, -1), clamp_min=self.stats_eps)
475
+ state_dim = int(state_mean.shape[-1])
476
+ action_dim = int(action_mean.shape[-1])
477
+
478
+ checkpoint_name = self._checkpoint_name_from_path(policy_path)
479
+ self.get_logger().info(
480
+ "ACT policy bundle loaded "
481
+ f"route={route_key} checkpoint={checkpoint_name} "
482
+ f"state_dim={state_dim} action_dim={action_dim}"
483
+ )
484
+
485
+ return LoadedACTPolicyBundle(
486
+ route_key=route_key,
487
+ policy_path=policy_path,
488
+ checkpoint_name=checkpoint_name,
489
+ policy=policy,
490
+ img_stats=img_stats,
491
+ state_mean=state_mean,
492
+ state_std=state_std,
493
+ action_mean=action_mean,
494
+ action_std=action_std,
495
+ state_dim=state_dim,
496
+ action_dim=action_dim,
497
+ )
498
+
499
+ def _validate_loaded_policy_bundles(self) -> None:
500
+ if not self._policy_bundles:
501
+ raise RuntimeError("No ACT policy bundles were resolved.")
502
+
503
+ bundles = list(self._policy_bundles.values())
504
+ reference_bundle = bundles[0]
505
+ for bundle in bundles[1:]:
506
+ if bundle.state_dim != reference_bundle.state_dim:
507
+ raise ValueError(
508
+ "ACT policy route mismatch: "
509
+ f"{bundle.route_key} state_dim={bundle.state_dim} "
510
+ f"!= {reference_bundle.route_key} state_dim={reference_bundle.state_dim}"
511
+ )
512
+ if bundle.action_dim != reference_bundle.action_dim:
513
+ raise ValueError(
514
+ "ACT policy route mismatch: "
515
+ f"{bundle.route_key} action_dim={bundle.action_dim} "
516
+ f"!= {reference_bundle.route_key} action_dim={reference_bundle.action_dim}"
517
+ )
518
+
519
+ def _activate_policy_bundle(self, route_key: str, reason: str = "") -> None:
520
+ bundle = self._policy_bundles[route_key]
521
+ self.policy = bundle.policy
522
+ self.policy_path = bundle.policy_path
523
+ self.checkpoint_name = bundle.checkpoint_name
524
+ self.img_stats = bundle.img_stats
525
+ self.state_mean = bundle.state_mean
526
+ self.state_std = bundle.state_std
527
+ self.action_mean = bundle.action_mean
528
+ self.action_std = bundle.action_std
529
+ self.state_dim = bundle.state_dim
530
+ self.action_dim = bundle.action_dim
531
+ self.command_mode = self._resolve_bundle_command_mode(bundle.action_dim)
532
+ self._active_policy_route = route_key
533
+
534
+ reason_suffix = f" reason={reason}" if reason else ""
535
+ self.get_logger().info(
536
+ "Activated ACT policy bundle "
537
+ f"route={route_key} checkpoint={self.checkpoint_name} "
538
+ f"command_mode={self.command_mode}{reason_suffix}"
539
+ )
540
+
541
+ @staticmethod
542
+ def _normalize_route_text(value: str | None) -> str:
543
+ normalized = (value or "").strip().lower()
544
+ return normalized
545
+
546
+ @staticmethod
547
+ def _family_route_from_text(normalized: str) -> str | None:
548
+ if not normalized:
549
+ return None
550
+ if normalized == "sc" or normalized.startswith("sc_") or "sc_port" in normalized:
551
+ return "sc"
552
+ if (
553
+ normalized == "sfp"
554
+ or normalized.startswith("sfp_")
555
+ or "sfp_port" in normalized
556
+ ):
557
+ return "sfp"
558
+ return None
559
+
560
+ def _infer_policy_route(self, task_msg: Task | None) -> str:
561
+ if task_msg is None:
562
+ return "default"
563
+
564
+ for value in (
565
+ getattr(task_msg, "port_type", None),
566
+ getattr(task_msg, "plug_type", None),
567
+ getattr(task_msg, "port_name", None),
568
+ getattr(task_msg, "target_module_name", None),
569
+ ):
570
+ normalized = self._normalize_route_text(value)
571
+ if not normalized:
572
+ continue
573
+ if normalized in self._policy_bundles:
574
+ return normalized
575
+ route_key = self._family_route_from_text(normalized)
576
+ if route_key is not None:
577
+ return route_key
578
+ return "default"
579
+
580
+ def _activate_policy_bundle_for_task(self, task_msg: Task | None) -> str:
581
+ inferred_route = self._infer_policy_route(task_msg)
582
+ selected_route = inferred_route
583
+ if selected_route not in self._policy_bundles:
584
+ selected_route = "default" if "default" in self._policy_bundles else next(
585
+ iter(self._policy_bundles)
586
+ )
587
+ if inferred_route != selected_route:
588
+ self.get_logger().info(
589
+ "No checkpoint configured for inferred route "
590
+ f"{inferred_route!r}; falling back to route={selected_route!r}"
591
+ )
592
+
593
+ task_id = getattr(task_msg, "id", "")
594
+ port_type = getattr(task_msg, "port_type", "")
595
+ plug_type = getattr(task_msg, "plug_type", "")
596
+ self._activate_policy_bundle(
597
+ selected_route,
598
+ reason=(
599
+ f"task_id={task_id or 'unknown'} "
600
+ f"port_type={port_type or 'unknown'} "
601
+ f"plug_type={plug_type or 'unknown'}"
602
+ ),
603
+ )
604
+ return selected_route
605
+
606
+ @staticmethod
607
+ def _img_to_tensor(
608
+ raw_img,
609
+ device: torch.device,
610
+ scale: float,
611
+ mean: torch.Tensor,
612
+ std: torch.Tensor,
613
+ ) -> torch.Tensor:
614
+ """Converts ROS Image -> Resized -> Permuted -> Normalized Tensor."""
615
+ # 1. Bytes to Numpy (H, W, C)
616
+ img_np = np.frombuffer(raw_img.data, dtype=np.uint8).reshape(
617
+ raw_img.height, raw_img.width, 3
618
+ )
619
+
620
+ # 2. Resize
621
+ if scale != 1.0:
622
+ img_np = cv2.resize(
623
+ img_np, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA
624
+ )
625
+
626
+ # 3. To Tensor -> Permute (HWC -> CHW) -> Float -> Div(255) -> Batch Dim
627
+ tensor = (
628
+ torch.from_numpy(img_np)
629
+ .permute(2, 0, 1)
630
+ .float()
631
+ .div(255.0)
632
+ .unsqueeze(0)
633
+ .to(device)
634
+ )
635
+
636
+ # 4. Normalize (Apply Mean/Std)
637
+ # Formula: (x - mean) / std
638
+ return (tensor - mean) / std
639
+
640
+ def _clock_now_seconds(self) -> float:
641
+ return float(self.time_now().nanoseconds) / 1e9
642
+
643
+ def _resolve_episode_root(self) -> Path | None:
644
+ root_env = os.environ.get("AIC_INSERTION_EPISODE_ROOT")
645
+ if root_env:
646
+ return Path(root_env).expanduser()
647
+
648
+ run_name = os.environ.get("AIC_RUN_NAME")
649
+ if run_name:
650
+ return Path("/ext/repo/aic_eval_runs") / run_name / "canonical_episodes"
651
+
652
+ return None
653
+
654
+ @staticmethod
655
+ def _stamp_to_seconds(stamp) -> float | None:
656
+ sec = getattr(stamp, "sec", None)
657
+ nanosec = getattr(stamp, "nanosec", None)
658
+ if sec is None or nanosec is None:
659
+ return None
660
+ return float(sec) + float(nanosec) / 1e9
661
+
662
+ def _latency_ms(self, stamp) -> float | None:
663
+ stamp_s = self._stamp_to_seconds(stamp)
664
+ if stamp_s is None:
665
+ return None
666
+ return max(0.0, (self._clock_now_seconds() - stamp_s) * 1000.0)
667
+
668
+ @staticmethod
669
+ def _generic_normalize_frame_name(frame_name: str) -> str:
670
+ return (frame_name or "").strip().strip("/").lower()
671
+
672
+ def _generic_scoring_tf_callback(self, msg: TFMessage) -> None:
673
+ if not self.generic_scoring_tf_diagnostics_enabled:
674
+ return
675
+ for transform in msg.transforms:
676
+ child_frame = self._generic_normalize_frame_name(
677
+ transform.child_frame_id
678
+ )
679
+ if not child_frame:
680
+ continue
681
+ translation = transform.transform.translation
682
+ self._generic_scoring_tf_positions[child_frame] = np.array(
683
+ [float(translation.x), float(translation.y), float(translation.z)],
684
+ dtype=np.float64,
685
+ )
686
+ self._generic_scoring_tf_raw_frames[child_frame] = (
687
+ transform.child_frame_id
688
+ )
689
+
690
+ def _generic_find_scoring_tf_position(
691
+ self,
692
+ token_groups: list[list[str]],
693
+ *,
694
+ reject_tokens: list[str] | None = None,
695
+ ) -> tuple[np.ndarray | None, str | None]:
696
+ normalized_rejects = [
697
+ self._generic_normalize_frame_name(token)
698
+ for token in (reject_tokens or [])
699
+ if token
700
+ ]
701
+ for tokens in token_groups:
702
+ normalized_tokens = [
703
+ self._generic_normalize_frame_name(token) for token in tokens if token
704
+ ]
705
+ if not normalized_tokens:
706
+ continue
707
+ for frame_name, position in self._generic_scoring_tf_positions.items():
708
+ if normalized_rejects and any(
709
+ reject in frame_name for reject in normalized_rejects
710
+ ):
711
+ continue
712
+ if all(token in frame_name for token in normalized_tokens):
713
+ return position, self._generic_scoring_tf_raw_frames.get(
714
+ frame_name, frame_name
715
+ )
716
+ return None, None
717
+
718
+ def _generic_plug_port_position_pair(
719
+ self, task: Task | None
720
+ ) -> tuple[
721
+ np.ndarray | None,
722
+ str | None,
723
+ np.ndarray | None,
724
+ str | None,
725
+ np.ndarray | None,
726
+ str | None,
727
+ ]:
728
+ if task is None:
729
+ return None, None, None, None, None, None
730
+
731
+ cable_name = getattr(task, "cable_name", "") or ""
732
+ plug_name = getattr(task, "plug_name", "") or ""
733
+ plug_type = getattr(task, "plug_type", "") or ""
734
+ target_module_name = getattr(task, "target_module_name", "") or ""
735
+ port_name = getattr(task, "port_name", "") or ""
736
+ port_type = getattr(task, "port_type", "") or ""
737
+ normalized_plug_type = plug_type.strip().lower()
738
+ normalized_port_text = f"{port_type} {port_name}".strip().lower()
739
+
740
+ plug_tokens: list[list[str]] = []
741
+ if plug_name:
742
+ plug_tokens.extend(
743
+ [
744
+ [cable_name, plug_name, "link"],
745
+ [cable_name, plug_name],
746
+ [plug_name, "link"],
747
+ [plug_name],
748
+ ]
749
+ )
750
+ if plug_type:
751
+ plug_tokens.extend(
752
+ [
753
+ [cable_name, f"{plug_type}_tip", "link"],
754
+ [cable_name, f"{plug_type}_tip"],
755
+ [plug_type, "tip", "link"],
756
+ [plug_type, "tip"],
757
+ ]
758
+ )
759
+ if normalized_plug_type == "sfp":
760
+ plug_tokens.extend([[cable_name, "sfp_tip"], ["sfp_tip"]])
761
+ elif normalized_plug_type == "sc":
762
+ plug_tokens.extend([[cable_name, "sc_tip"], ["sc_tip"]])
763
+ else:
764
+ plug_tokens.extend(
765
+ [
766
+ [cable_name, "sfp_tip"],
767
+ [cable_name, "sc_tip"],
768
+ ["sfp_tip"],
769
+ ["sc_tip"],
770
+ ]
771
+ )
772
+ plug_position, plug_frame = self._generic_find_scoring_tf_position(
773
+ plug_tokens,
774
+ reject_tokens=["collision", "visual", "collider"],
775
+ )
776
+
777
+ port_tokens: list[list[str]] = []
778
+ entrance_tokens: list[list[str]] = []
779
+ if port_name:
780
+ port_tokens.extend(
781
+ [
782
+ [target_module_name, f"{port_name}_link"],
783
+ [target_module_name, port_name, "link"],
784
+ [target_module_name, port_name],
785
+ [port_name, "link"],
786
+ [port_name],
787
+ ]
788
+ )
789
+ entrance_tokens.extend(
790
+ [
791
+ [target_module_name, f"{port_name}_link_entrance"],
792
+ [target_module_name, port_name, "entrance"],
793
+ [port_name, "link_entrance"],
794
+ [port_name, "entrance"],
795
+ ]
796
+ )
797
+ if "sc" in normalized_port_text:
798
+ port_tokens.extend(
799
+ [
800
+ [target_module_name, "sc_port_base", "link"],
801
+ [target_module_name, "sc_port_base"],
802
+ ["sc_port_base", "link"],
803
+ ["sc_port_base"],
804
+ ]
805
+ )
806
+ entrance_tokens.extend(
807
+ [
808
+ [target_module_name, "sc_port_base", "entrance"],
809
+ ["sc_port_base", "entrance"],
810
+ ]
811
+ )
812
+
813
+ port_position, port_frame = self._generic_find_scoring_tf_position(
814
+ port_tokens,
815
+ reject_tokens=["entrance", "collision", "visual", "collider"],
816
+ )
817
+ entrance_position, entrance_frame = self._generic_find_scoring_tf_position(
818
+ entrance_tokens,
819
+ reject_tokens=["collision", "visual", "collider"],
820
+ )
821
+ return (
822
+ plug_position,
823
+ plug_frame,
824
+ port_position,
825
+ port_frame,
826
+ entrance_position,
827
+ entrance_frame,
828
+ )
829
+
830
+ @staticmethod
831
+ def _generic_safe_unit(vector: np.ndarray) -> np.ndarray | None:
832
+ norm = float(np.linalg.norm(vector))
833
+ if norm < 1e-8:
834
+ return None
835
+ return vector / norm
836
+
837
+ def _generic_insert_axis(
838
+ self,
839
+ *,
840
+ port_position: np.ndarray | None,
841
+ entrance_position: np.ndarray | None,
842
+ ) -> np.ndarray | None:
843
+ if port_position is None or entrance_position is None:
844
+ return None
845
+ return self._generic_safe_unit(entrance_position - port_position)
846
+
847
+ def _generic_build_insert_frame_basis(
848
+ self, insert_axis: np.ndarray
849
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
850
+ axial_axis = self._generic_safe_unit(insert_axis)
851
+ if axial_axis is None:
852
+ raise ValueError("Cannot build insertion frame without a valid insert axis.")
853
+ reference = np.array([0.0, 0.0, 1.0], dtype=np.float64)
854
+ if abs(float(np.dot(reference, axial_axis))) > 0.95:
855
+ reference = np.array([1.0, 0.0, 0.0], dtype=np.float64)
856
+ lateral_u = self._generic_safe_unit(np.cross(reference, axial_axis))
857
+ if lateral_u is None:
858
+ lateral_u = np.array([1.0, 0.0, 0.0], dtype=np.float64)
859
+ lateral_v = self._generic_safe_unit(np.cross(axial_axis, lateral_u))
860
+ if lateral_v is None:
861
+ lateral_v = np.array([0.0, 1.0, 0.0], dtype=np.float64)
862
+ return lateral_u, lateral_v, axial_axis
863
+
864
+ def _generic_vector_to_insert_frame(
865
+ self, insert_axis: np.ndarray, world_vector: np.ndarray
866
+ ) -> np.ndarray:
867
+ lateral_u, lateral_v, axial_axis = self._generic_build_insert_frame_basis(
868
+ insert_axis
869
+ )
870
+ return np.array(
871
+ [
872
+ float(np.dot(world_vector, lateral_u)),
873
+ float(np.dot(world_vector, lateral_v)),
874
+ float(np.dot(world_vector, axial_axis)),
875
+ ],
876
+ dtype=np.float64,
877
+ )
878
+
879
+ def _update_generic_plug_port_geometry(
880
+ self,
881
+ task: Task | None,
882
+ ) -> dict[str, object]:
883
+ if not self.generic_scoring_tf_diagnostics_enabled:
884
+ return {
885
+ "scoring_tf_diagnostics_enabled": False,
886
+ "plug_port_geometry_available": False,
887
+ }
888
+ if task is None:
889
+ geometry = {
890
+ "scoring_tf_diagnostics_enabled": True,
891
+ "plug_port_geometry_available": False,
892
+ "plug_port_geometry_reason": "no_task",
893
+ "scoring_tf_frame_count": len(self._generic_scoring_tf_positions),
894
+ }
895
+ self._generic_last_plug_port_geometry = geometry
896
+ return geometry
897
+
898
+ (
899
+ plug_position,
900
+ plug_frame,
901
+ port_position,
902
+ port_frame,
903
+ entrance_position,
904
+ entrance_frame,
905
+ ) = self._generic_plug_port_position_pair(task)
906
+ if plug_position is None or port_position is None:
907
+ geometry = {
908
+ "scoring_tf_diagnostics_enabled": True,
909
+ "plug_port_geometry_available": False,
910
+ "plug_tip_frame": plug_frame,
911
+ "target_port_frame": port_frame,
912
+ "target_port_entrance_frame": entrance_frame,
913
+ "plug_port_geometry_reason": "missing_frame",
914
+ "scoring_tf_frame_count": len(self._generic_scoring_tf_positions),
915
+ }
916
+ self._generic_last_plug_port_geometry = geometry
917
+ return geometry
918
+
919
+ delta = plug_position - port_position
920
+ distance_m = float(np.linalg.norm(delta))
921
+ insert_axis = self._generic_insert_axis(
922
+ port_position=port_position,
923
+ entrance_position=entrance_position,
924
+ )
925
+ axial_offset_m: float | None = None
926
+ lateral_distance_m: float | None = None
927
+ insertion_depth_estimate_m: float | None = None
928
+ delta_insert_frame_m: list[float] | None = None
929
+ lateral_correction_insert_frame_m: list[float] | None = None
930
+ lateral_correction_world_m: list[float] | None = None
931
+ if insert_axis is not None:
932
+ axial_offset_m = float(np.dot(delta, insert_axis))
933
+ lateral_vector = delta - insert_axis * axial_offset_m
934
+ lateral_distance_m = float(np.linalg.norm(lateral_vector))
935
+ delta_insert_frame = self._generic_vector_to_insert_frame(
936
+ insert_axis, delta
937
+ )
938
+ delta_insert_frame_m = delta_insert_frame.astype(float).tolist()
939
+ lateral_correction_insert_frame = np.array(
940
+ [-delta_insert_frame[0], -delta_insert_frame[1], 0.0],
941
+ dtype=np.float64,
942
+ )
943
+ lateral_correction_insert_frame_m = (
944
+ lateral_correction_insert_frame.astype(float).tolist()
945
+ )
946
+ lateral_correction_world_m = (
947
+ -lateral_vector.astype(np.float64)
948
+ ).astype(float).tolist()
949
+ insertion_depth_estimate_m = max(0.0, -axial_offset_m)
950
+
951
+ insertion_event_seen = bool(getattr(self, "_insertion_event_seen", False))
952
+ if insertion_event_seen:
953
+ seatedness = "insertion_event"
954
+ elif distance_m <= 0.025:
955
+ seatedness = "near_or_partial"
956
+ elif distance_m <= 0.060:
957
+ seatedness = "near_mouth"
958
+ else:
959
+ seatedness = "not_at_mouth"
960
+
961
+ geometry = {
962
+ "diagnostic_source": "generic_scoring_tf",
963
+ "scoring_tf_diagnostics_enabled": True,
964
+ "plug_port_geometry_available": True,
965
+ "plug_tip_frame": plug_frame,
966
+ "target_port_frame": port_frame,
967
+ "target_port_entrance_frame": entrance_frame,
968
+ "coordinate_frame": "scoring_tf_world",
969
+ "plug_tip_world_m": plug_position.astype(float).tolist(),
970
+ "target_port_world_m": port_position.astype(float).tolist(),
971
+ "port_entrance_world_m": entrance_position.astype(float).tolist()
972
+ if entrance_position is not None
973
+ else None,
974
+ "insert_axis_source": "port_to_entrance"
975
+ if insert_axis is not None
976
+ else "unavailable",
977
+ "insert_axis_world_m": insert_axis.astype(float).tolist()
978
+ if insert_axis is not None
979
+ else None,
980
+ "plug_port_distance_m": distance_m,
981
+ "plug_port_delta_world_m": delta.astype(float).tolist(),
982
+ "plug_to_port_correction_world_m": (-delta).astype(float).tolist(),
983
+ "plug_port_delta_insert_frame_m": delta_insert_frame_m,
984
+ "lateral_correction_insert_frame_m": lateral_correction_insert_frame_m,
985
+ "lateral_correction_world_m": lateral_correction_world_m,
986
+ "plug_port_lateral_distance_m": lateral_distance_m,
987
+ "plug_port_axial_offset_m": axial_offset_m,
988
+ "insertion_depth_estimate_m": insertion_depth_estimate_m,
989
+ "seatedness_estimate": seatedness,
990
+ "scoring_tf_frame_count": len(self._generic_scoring_tf_positions),
991
+ }
992
+ self._generic_last_plug_port_geometry = geometry
993
+ if (
994
+ self._generic_best_plug_port_distance_m is None
995
+ or distance_m < self._generic_best_plug_port_distance_m
996
+ ):
997
+ self._generic_best_plug_port_distance_m = distance_m
998
+ self._generic_best_plug_port_geometry = dict(geometry)
999
+ return geometry
1000
+
1001
+ @staticmethod
1002
+ def _clip_runtime_geometry_label(
1003
+ vector: np.ndarray, max_norm_m: float
1004
+ ) -> tuple[np.ndarray, bool]:
1005
+ norm = float(np.linalg.norm(vector))
1006
+ if norm <= max_norm_m or norm <= 1e-12:
1007
+ return vector.astype(np.float64), False
1008
+ return (vector / norm * max_norm_m).astype(np.float64), True
1009
+
1010
+ def _append_generic_runtime_geometry_label(
1011
+ self, *, observation: dict[str, Any], geometry: dict[str, object]
1012
+ ) -> None:
1013
+ if not self._runtime_geometry_jsonl_path:
1014
+ return
1015
+
1016
+ robot = observation.get("robot") or {}
1017
+ raw_force_torque = list(robot.get("force_torque") or [])
1018
+ tare_offset_force_torque = list(robot.get("tare_offset_force_torque") or [])
1019
+ compensated_force_torque: list[float] | None = None
1020
+ if len(raw_force_torque) >= 6 and len(tare_offset_force_torque) >= 6:
1021
+ compensated_force_torque = (
1022
+ np.asarray(raw_force_torque[:6], dtype=np.float64)
1023
+ - np.asarray(tare_offset_force_torque[:6], dtype=np.float64)
1024
+ ).astype(float).tolist()
1025
+ force_torque = compensated_force_torque or raw_force_torque
1026
+ force_vector = (
1027
+ np.asarray(force_torque[:3], dtype=np.float64)
1028
+ if len(force_torque) >= 3
1029
+ else None
1030
+ )
1031
+ insert_axis_raw = geometry.get("insert_axis_world_m")
1032
+ insert_axis = (
1033
+ np.asarray(insert_axis_raw, dtype=np.float64)
1034
+ if isinstance(insert_axis_raw, list) and len(insert_axis_raw) >= 3
1035
+ else None
1036
+ )
1037
+ if insert_axis is not None:
1038
+ axis_norm = float(np.linalg.norm(insert_axis))
1039
+ insert_axis = insert_axis / axis_norm if axis_norm > 1e-12 else None
1040
+
1041
+ force_magnitude_n: float | None = None
1042
+ axial_force_abs_n: float | None = None
1043
+ lateral_force_n: float | None = None
1044
+ if force_vector is not None and np.isfinite(force_vector).all():
1045
+ force_magnitude_n = float(np.linalg.norm(force_vector))
1046
+ if insert_axis is not None:
1047
+ axial_force = float(np.dot(force_vector, insert_axis))
1048
+ axial_force_abs_n = abs(axial_force)
1049
+ lateral_force_n = float(
1050
+ np.linalg.norm(force_vector - insert_axis * axial_force)
1051
+ )
1052
+
1053
+ label = None
1054
+ label_mode = "missing_runtime_lateral_correction"
1055
+ label_clipped = False
1056
+ correction_raw = geometry.get("lateral_correction_world_m")
1057
+ if isinstance(correction_raw, list) and len(correction_raw) >= 3:
1058
+ correction = np.asarray(correction_raw[:3], dtype=np.float64)
1059
+ if np.isfinite(correction).all():
1060
+ label, label_clipped = self._clip_runtime_geometry_label(
1061
+ correction,
1062
+ max(0.0, float(self._runtime_geometry_label_max_translation_m)),
1063
+ )
1064
+ label_mode = "runtime_lateral_correction_world"
1065
+ if label_clipped:
1066
+ label_mode += "+translation_clipped"
1067
+
1068
+ action_6 = None
1069
+ if label is not None:
1070
+ action_6 = [float(label[0]), float(label[1]), float(label[2]), 0.0, 0.0, 0.0]
1071
+
1072
+ delta_raw = geometry.get("plug_port_delta_world_m")
1073
+ direction_verified = None
1074
+ if (
1075
+ label is not None
1076
+ and insert_axis is not None
1077
+ and isinstance(delta_raw, list)
1078
+ and len(delta_raw) >= 3
1079
+ ):
1080
+ delta = np.asarray(delta_raw[:3], dtype=np.float64)
1081
+ axial_offset = float(np.dot(delta, insert_axis))
1082
+ lateral_residual = delta - insert_axis * axial_offset
1083
+ direction_verified = bool(float(np.dot(label, -lateral_residual)) >= -1e-9)
1084
+
1085
+ payload = {
1086
+ "schema": "act_runtime_lateral_correction_v1",
1087
+ "timestamp": float(observation["timestamp"]),
1088
+ "frame_index": None,
1089
+ "runtime_frame_index": int(self._runtime_geometry_seq),
1090
+ "sequence": int(self._runtime_geometry_seq),
1091
+ "policy": self._canonical_policy_name(),
1092
+ "checkpoint": self.checkpoint_name,
1093
+ "checkpoint_route": self._active_policy_route,
1094
+ "policy_phase": observation.get("policy_phase"),
1095
+ "task": self._task_metadata_dict(self._active_task),
1096
+ "coordinate_frame": geometry.get("coordinate_frame", "scoring_tf_world"),
1097
+ "tcp_pose_world": {
1098
+ "position": list(robot.get("end_effector_position") or []),
1099
+ "quaternion": list(robot.get("end_effector_quaternion") or []),
1100
+ },
1101
+ "tcp_pose_world_m": list(robot.get("end_effector_position") or []),
1102
+ "plug_tip_world_m": geometry.get("plug_tip_world_m"),
1103
+ "target_port_world_m": geometry.get("target_port_world_m"),
1104
+ "port_entrance_world_m": geometry.get("port_entrance_world_m"),
1105
+ "plug_tip_frame": geometry.get("plug_tip_frame"),
1106
+ "target_port_frame": geometry.get("target_port_frame"),
1107
+ "target_port_entrance_frame": geometry.get("target_port_entrance_frame"),
1108
+ "plug_port_geometry_available": geometry.get(
1109
+ "plug_port_geometry_available"
1110
+ ),
1111
+ "plug_port_geometry_reason": geometry.get("plug_port_geometry_reason"),
1112
+ "insert_axis_source": geometry.get("insert_axis_source"),
1113
+ "insert_axis_world_m": geometry.get("insert_axis_world_m"),
1114
+ "plug_port_delta_world_m": geometry.get("plug_port_delta_world_m"),
1115
+ "plug_port_delta_insert_frame_m": geometry.get(
1116
+ "plug_port_delta_insert_frame_m"
1117
+ ),
1118
+ "lateral_correction_insert_frame_m": geometry.get(
1119
+ "lateral_correction_insert_frame_m"
1120
+ ),
1121
+ "lateral_correction_world_m": geometry.get("lateral_correction_world_m"),
1122
+ "label_lateral_correction_world_clipped_m": label.astype(float).tolist()
1123
+ if label is not None
1124
+ else None,
1125
+ "action_6_label_world_m": action_6,
1126
+ "action_label_mode": label_mode,
1127
+ "action_label_max_translation_m": float(
1128
+ self._runtime_geometry_label_max_translation_m
1129
+ ),
1130
+ "action_label_clipped": bool(label_clipped),
1131
+ "direction_verified": direction_verified,
1132
+ "plug_port_distance_m": geometry.get("plug_port_distance_m"),
1133
+ "plug_port_lateral_distance_m": geometry.get(
1134
+ "plug_port_lateral_distance_m"
1135
+ ),
1136
+ "plug_port_axial_offset_m": geometry.get("plug_port_axial_offset_m"),
1137
+ "insertion_depth_estimate_m": geometry.get("insertion_depth_estimate_m"),
1138
+ "seatedness_estimate": geometry.get("seatedness_estimate"),
1139
+ "force_torque": force_torque,
1140
+ "force_torque_source": (
1141
+ "observation.wrist_wrench_minus_controller_state.fts_tare_offset"
1142
+ if compensated_force_torque is not None
1143
+ else robot.get("force_torque_source")
1144
+ ),
1145
+ "raw_force_torque": raw_force_torque,
1146
+ "raw_force_torque_source": robot.get("force_torque_source"),
1147
+ "tare_offset_force_torque": tare_offset_force_torque,
1148
+ "force_vector_n": force_torque[:3] if len(force_torque) >= 3 else None,
1149
+ "force_magnitude_n": force_magnitude_n,
1150
+ "axial_force_abs_n": axial_force_abs_n,
1151
+ "lateral_force_n": lateral_force_n,
1152
+ "force_safe_limit_n": float(self._runtime_geometry_force_safe_n),
1153
+ "lateral_force_safe_limit_n": float(
1154
+ self._runtime_geometry_lateral_force_safe_n
1155
+ ),
1156
+ "force_safe": (
1157
+ None
1158
+ if force_magnitude_n is None
1159
+ else force_magnitude_n <= self._runtime_geometry_force_safe_n
1160
+ ),
1161
+ "lateral_force_safe": (
1162
+ None
1163
+ if lateral_force_n is None
1164
+ else lateral_force_n <= self._runtime_geometry_lateral_force_safe_n
1165
+ ),
1166
+ "wrapper_valid": bool(observation.get("wrapper_valid", False)),
1167
+ "invalid_reason": observation.get("invalid_reason"),
1168
+ }
1169
+
1170
+ path = Path(self._runtime_geometry_jsonl_path).expanduser()
1171
+ path.parent.mkdir(parents=True, exist_ok=True)
1172
+ with path.open("a", encoding="utf-8") as fh:
1173
+ json.dump(payload, fh, sort_keys=True)
1174
+ fh.write("\n")
1175
+ self._runtime_geometry_seq += 1
1176
+
1177
+ def _log_generic_runtime_geometry_diagnostics(
1178
+ self, *, wrapper_returned_success: bool, termination_reason: str
1179
+ ) -> None:
1180
+ if not self.generic_scoring_tf_diagnostics_enabled:
1181
+ return
1182
+ if self._active_task is not None:
1183
+ self._update_generic_plug_port_geometry(self._active_task)
1184
+ self.get_logger().info(
1185
+ "ACT_RUNTIME_GEOMETRY diagnostics "
1186
+ f"policy={self._canonical_policy_name()} "
1187
+ f"checkpoint={self.checkpoint_name} "
1188
+ f"checkpoint_route={self._active_policy_route} "
1189
+ f"wrapper_returned_success={wrapper_returned_success} "
1190
+ f"termination_reason={termination_reason} "
1191
+ f"insertion_event_seen={bool(getattr(self, '_insertion_event_seen', False))} "
1192
+ f"last_insertion_event={getattr(self, '_last_insertion_event', '')!r} "
1193
+ f"last_plug_port_geometry={self._generic_last_plug_port_geometry} "
1194
+ f"best_plug_port_distance_m={self._generic_best_plug_port_distance_m} "
1195
+ f"best_plug_port_geometry={self._generic_best_plug_port_geometry}"
1196
+ )
1197
+
1198
+ @staticmethod
1199
+ def _gripper_state_from_joint_positions(joint_positions: list[float]) -> str:
1200
+ if len(joint_positions) < 7:
1201
+ return "unknown"
1202
+ return "open" if joint_positions[6] > 0.0125 else "closed"
1203
+
1204
+ def _build_raw_state_vector(
1205
+ self, obs_msg: Observation, task_msg: Task | None
1206
+ ) -> np.ndarray:
1207
+ controller_state = obs_msg.controller_state
1208
+ tcp_pose = controller_state.tcp_pose
1209
+ tcp_vel = controller_state.tcp_velocity
1210
+ tare_wrench = controller_state.fts_tare_offset.wrench
1211
+ joint_positions = list(obs_msg.joint_states.position)
1212
+ joint_velocities = (
1213
+ list(obs_msg.joint_states.velocity)
1214
+ if obs_msg.joint_states.velocity
1215
+ else []
1216
+ )
1217
+ task_features = _encode_task_numeric(task_msg)
1218
+
1219
+ return np.array(
1220
+ [
1221
+ tcp_pose.position.x,
1222
+ tcp_pose.position.y,
1223
+ tcp_pose.position.z,
1224
+ tcp_pose.orientation.x,
1225
+ tcp_pose.orientation.y,
1226
+ tcp_pose.orientation.z,
1227
+ tcp_pose.orientation.w,
1228
+ tcp_vel.linear.x,
1229
+ tcp_vel.linear.y,
1230
+ tcp_vel.linear.z,
1231
+ tcp_vel.angular.x,
1232
+ tcp_vel.angular.y,
1233
+ tcp_vel.angular.z,
1234
+ *controller_state.tcp_error,
1235
+ *[
1236
+ (joint_positions[i] if i < len(joint_positions) else 0.0)
1237
+ for i in range(7)
1238
+ ],
1239
+ *[
1240
+ (joint_velocities[i] if i < len(joint_velocities) else 0.0)
1241
+ for i in range(7)
1242
+ ],
1243
+ tare_wrench.force.x,
1244
+ tare_wrench.force.y,
1245
+ tare_wrench.force.z,
1246
+ tare_wrench.torque.x,
1247
+ tare_wrench.torque.y,
1248
+ tare_wrench.torque.z,
1249
+ task_features["task.target_valid"],
1250
+ task_features["task.cable_type_id"],
1251
+ task_features["task.plug_type_id"],
1252
+ task_features["task.port_type_id"],
1253
+ task_features["task.target_module_id"],
1254
+ task_features["task.target_port_id"],
1255
+ task_features["task.target_module_index"],
1256
+ task_features["task.target_port_index"],
1257
+ task_features["task.time_limit"],
1258
+ ],
1259
+ dtype=np.float32,
1260
+ )
1261
+
1262
+ def _build_cv_observation(
1263
+ self, obs_msg: Observation, task_msg: Task | None
1264
+ ) -> dict[str, Any]:
1265
+ features = self._cv_extractor.extract(
1266
+ raw_img=obs_msg.center_image,
1267
+ task_msg=task_msg,
1268
+ )
1269
+ latency_ms = self._latency_ms(obs_msg.center_image.header.stamp)
1270
+ stale = bool(
1271
+ latency_ms is not None and latency_ms > self.cv_stale_threshold_ms
1272
+ )
1273
+ detection_conf = float(
1274
+ min(features.segmentation_confidence, features.selection_confidence)
1275
+ )
1276
+ detections = []
1277
+ if features.target_valid >= 0.5:
1278
+ detections.append(
1279
+ {
1280
+ "class": "target_port",
1281
+ "confidence": detection_conf,
1282
+ "target_valid": features.target_valid,
1283
+ "center_u_norm": features.target_center_u_norm,
1284
+ "center_v_norm": features.target_center_v_norm,
1285
+ "scale_norm": features.target_scale_norm,
1286
+ "bearing_x": features.target_bearing_x,
1287
+ "bearing_y": features.target_bearing_y,
1288
+ "segmentation_confidence": features.segmentation_confidence,
1289
+ "selection_confidence": features.selection_confidence,
1290
+ }
1291
+ )
1292
+ return {
1293
+ "timestamp": self._clock_now_seconds(),
1294
+ "camera": "center",
1295
+ "latency_ms": latency_ms,
1296
+ "stale": stale,
1297
+ "detections": detections,
1298
+ "feature_vector": features.as_dict(),
1299
+ }
1300
+
1301
+ def _set_active_runtime_context(
1302
+ self,
1303
+ *,
1304
+ observation_msg: Observation,
1305
+ task_msg: Task | None,
1306
+ move_robot: MoveRobotCallback | None = None,
1307
+ ) -> None:
1308
+ self._active_observation_msg = observation_msg
1309
+ self._active_task = task_msg
1310
+ if move_robot is not None:
1311
+ self._active_move_robot = move_robot
1312
+ self._latest_cv_observation = self._build_cv_observation(
1313
+ observation_msg, task_msg
1314
+ )
1315
+
1316
+ def get_policy_observation(self) -> dict[str, Any]:
1317
+ if self._active_observation_msg is None:
1318
+ raise RuntimeError("No active observation is available for the wrapper.")
1319
+
1320
+ obs_msg = self._active_observation_msg
1321
+ controller_state = obs_msg.controller_state
1322
+ joint_positions = list(obs_msg.joint_states.position)
1323
+ joint_velocities = (
1324
+ list(obs_msg.joint_states.velocity)
1325
+ if obs_msg.joint_states.velocity
1326
+ else []
1327
+ )
1328
+ raw_state = self._build_raw_state_vector(obs_msg, self._active_task)
1329
+ if self._latest_cv_observation is None:
1330
+ self._latest_cv_observation = self._build_cv_observation(
1331
+ obs_msg, self._active_task
1332
+ )
1333
+
1334
+ wrist_wrench = obs_msg.wrist_wrench.wrench
1335
+ tare_wrench = controller_state.fts_tare_offset.wrench
1336
+ robot_state_latency_ms = self._latency_ms(controller_state.header.stamp)
1337
+ force_latency_ms = self._latency_ms(obs_msg.wrist_wrench.header.stamp)
1338
+ cv_latency_ms = self._latest_cv_observation.get("latency_ms")
1339
+ cv_stale = bool(self._latest_cv_observation.get("stale", False))
1340
+
1341
+ invalid_reason = None
1342
+ if not np.isfinite(raw_state).all():
1343
+ invalid_reason = "non_finite_state"
1344
+ elif robot_state_latency_ms is not None and (
1345
+ robot_state_latency_ms > self.robot_state_stale_threshold_ms
1346
+ ):
1347
+ invalid_reason = "stale_robot_state"
1348
+ elif cv_stale:
1349
+ invalid_reason = "stale_cv_output"
1350
+
1351
+ observation = {
1352
+ "timestamp": self._clock_now_seconds(),
1353
+ "robot": {
1354
+ "end_effector_position": [
1355
+ controller_state.tcp_pose.position.x,
1356
+ controller_state.tcp_pose.position.y,
1357
+ controller_state.tcp_pose.position.z,
1358
+ ],
1359
+ "end_effector_quaternion": [
1360
+ controller_state.tcp_pose.orientation.x,
1361
+ controller_state.tcp_pose.orientation.y,
1362
+ controller_state.tcp_pose.orientation.z,
1363
+ controller_state.tcp_pose.orientation.w,
1364
+ ],
1365
+ "end_effector_linear_velocity": [
1366
+ controller_state.tcp_velocity.linear.x,
1367
+ controller_state.tcp_velocity.linear.y,
1368
+ controller_state.tcp_velocity.linear.z,
1369
+ ],
1370
+ "end_effector_angular_velocity": [
1371
+ controller_state.tcp_velocity.angular.x,
1372
+ controller_state.tcp_velocity.angular.y,
1373
+ controller_state.tcp_velocity.angular.z,
1374
+ ],
1375
+ "joint_positions": joint_positions,
1376
+ "joint_velocities": joint_velocities,
1377
+ "force_torque": [
1378
+ wrist_wrench.force.x,
1379
+ wrist_wrench.force.y,
1380
+ wrist_wrench.force.z,
1381
+ wrist_wrench.torque.x,
1382
+ wrist_wrench.torque.y,
1383
+ wrist_wrench.torque.z,
1384
+ ],
1385
+ "force_torque_source": "observation.wrist_wrench",
1386
+ "tare_offset_force_torque": [
1387
+ tare_wrench.force.x,
1388
+ tare_wrench.force.y,
1389
+ tare_wrench.force.z,
1390
+ tare_wrench.torque.x,
1391
+ tare_wrench.torque.y,
1392
+ tare_wrench.torque.z,
1393
+ ],
1394
+ "gripper_state": self._gripper_state_from_joint_positions(
1395
+ joint_positions
1396
+ ),
1397
+ },
1398
+ "controller_state_48": raw_state.tolist(),
1399
+ "controller_state_names": list(self.state_feature_names),
1400
+ "cv_observation": self._latest_cv_observation,
1401
+ "cv_stale": cv_stale,
1402
+ "cv_latency_ms": cv_latency_ms,
1403
+ "robot_state_latency_ms": robot_state_latency_ms,
1404
+ "force_latency_ms": force_latency_ms,
1405
+ "wrapper_valid": invalid_reason is None,
1406
+ "invalid_reason": invalid_reason,
1407
+ "previous_action": self._previous_action_record,
1408
+ "policy_phase": getattr(self, "_phase", None),
1409
+ "policy_route": self._active_policy_route,
1410
+ "available_policy_routes": sorted(self._policy_bundles.keys()),
1411
+ }
1412
+ if self.generic_scoring_tf_diagnostics_enabled:
1413
+ geometry = self._update_generic_plug_port_geometry(self._active_task)
1414
+ observation["plug_port_geometry"] = geometry
1415
+ self._append_generic_runtime_geometry_label(
1416
+ observation=observation,
1417
+ geometry=geometry,
1418
+ )
1419
+ self._last_policy_observation = observation
1420
+ return observation
1421
+
1422
+ def _task_metadata_dict(self, task_msg: Task | None) -> dict[str, Any]:
1423
+ if task_msg is None:
1424
+ return {
1425
+ "id": "",
1426
+ "cable_type": "unknown",
1427
+ "cable_name": "",
1428
+ "plug_type": "unknown",
1429
+ "plug_name": "",
1430
+ "port_type": "unknown",
1431
+ "port_name": "",
1432
+ "target_module_name": "",
1433
+ "time_limit": 0,
1434
+ }
1435
+
1436
+ return {
1437
+ "id": task_msg.id,
1438
+ "cable_type": task_msg.cable_type,
1439
+ "cable_name": task_msg.cable_name,
1440
+ "plug_type": task_msg.plug_type,
1441
+ "plug_name": task_msg.plug_name,
1442
+ "port_type": task_msg.port_type,
1443
+ "port_name": task_msg.port_name,
1444
+ "target_module_name": task_msg.target_module_name,
1445
+ "time_limit": int(task_msg.time_limit),
1446
+ }
1447
+
1448
+ def _canonical_policy_name(self) -> str:
1449
+ return self.__class__.__name__
1450
+
1451
+ def _begin_canonical_episode(self, task_msg: Task | None) -> None:
1452
+ self._close_episode_writer()
1453
+ self._episode_action_id = 0
1454
+ self._episode_last_action_result = None
1455
+ self._episode_last_wrapper_output = None
1456
+ self._episode_start_time_s = self._clock_now_seconds()
1457
+
1458
+ if self._episode_root is None:
1459
+ return
1460
+
1461
+ task_dict = self._task_metadata_dict(task_msg)
1462
+ task_id = task_dict.get("id") or task_dict.get("port_name") or "task"
1463
+ episode_id = build_episode_id(
1464
+ self._episode_run_name,
1465
+ str(task_id),
1466
+ self._episode_start_time_s,
1467
+ )
1468
+ metadata = {
1469
+ "schema_version": "insertion_episode/v1",
1470
+ "episode_id": episode_id,
1471
+ "source": self._episode_source,
1472
+ "date_collected": utc_now_iso(),
1473
+ "task": task_dict,
1474
+ "policy_type": self._canonical_policy_name(),
1475
+ "environment": self._episode_environment,
1476
+ "robot_type": self._episode_robot_type,
1477
+ "camera_streams": [],
1478
+ "action_space": "cartesian_pose_or_twist",
1479
+ "action_dim": int(self.action_dim),
1480
+ "checkpoint": self.checkpoint_name,
1481
+ "checkpoint_path": str(self.policy_path),
1482
+ "checkpoint_route": self._active_policy_route,
1483
+ "available_checkpoint_routes": sorted(self._policy_bundles.keys()),
1484
+ "connector_type": self._episode_connector_type,
1485
+ "target": {
1486
+ "module_name": task_dict.get("target_module_name"),
1487
+ "port_name": task_dict.get("port_name"),
1488
+ "port_type": task_dict.get("port_type"),
1489
+ },
1490
+ "wrapper_name": self._canonical_policy_name(),
1491
+ "observation_state_dim": int(self.state_dim),
1492
+ "observation_state_names": list(self.state_feature_names),
1493
+ }
1494
+ self._episode_writer = CanonicalEpisodeWriter(
1495
+ dataset_root=self._episode_root,
1496
+ episode_id=episode_id,
1497
+ metadata=metadata,
1498
+ )
1499
+
1500
+ def _close_episode_writer(self) -> None:
1501
+ if self._episode_writer is not None:
1502
+ self._episode_writer.close()
1503
+ self._episode_writer = None
1504
+
1505
+ def _build_robot_state_row(self, observation: dict[str, Any]) -> dict[str, Any]:
1506
+ robot = observation["robot"]
1507
+ row = {
1508
+ "timestamp": observation["timestamp"],
1509
+ "joint_positions": list(robot["joint_positions"]),
1510
+ "joint_velocities": list(robot["joint_velocities"]),
1511
+ "end_effector_position": list(robot["end_effector_position"]),
1512
+ "end_effector_quaternion": list(robot["end_effector_quaternion"]),
1513
+ "gripper_state": robot["gripper_state"],
1514
+ "end_effector_linear_velocity": list(
1515
+ robot["end_effector_linear_velocity"]
1516
+ ),
1517
+ "end_effector_angular_velocity": list(
1518
+ robot["end_effector_angular_velocity"]
1519
+ ),
1520
+ "force_torque": list(robot["force_torque"]),
1521
+ "force_torque_source": robot.get("force_torque_source"),
1522
+ "tare_offset_force_torque": list(robot.get("tare_offset_force_torque") or []),
1523
+ "wrapper_valid": bool(observation["wrapper_valid"]),
1524
+ "invalid_reason": observation["invalid_reason"],
1525
+ "policy_phase": observation.get("policy_phase"),
1526
+ "robot_state_latency_ms": observation.get("robot_state_latency_ms"),
1527
+ }
1528
+ if "plug_port_geometry" in observation:
1529
+ row["plug_port_geometry"] = observation.get("plug_port_geometry")
1530
+ return row
1531
+
1532
+ def _build_force_torque_row(self, observation: dict[str, Any]) -> dict[str, Any]:
1533
+ force_latency_ms = observation.get("force_latency_ms")
1534
+ return {
1535
+ "timestamp": observation["timestamp"],
1536
+ "force_torque": list(observation["robot"]["force_torque"]),
1537
+ "latency_ms": force_latency_ms,
1538
+ "stale": bool(
1539
+ force_latency_ms is not None
1540
+ and force_latency_ms > self.force_stale_threshold_ms
1541
+ ),
1542
+ }
1543
+
1544
+ def _build_cv_output_row(self, observation: dict[str, Any]) -> dict[str, Any]:
1545
+ cv_observation = dict(observation["cv_observation"])
1546
+ cv_observation.setdefault("timestamp", observation["timestamp"])
1547
+ cv_observation["cv_stale"] = bool(observation.get("cv_stale", False))
1548
+ cv_observation["cv_latency_ms"] = observation.get("cv_latency_ms")
1549
+ return cv_observation
1550
+
1551
+ def _write_policy_observation(self, observation: dict[str, Any]) -> None:
1552
+ if self._episode_writer is None:
1553
+ return
1554
+ self._episode_writer.write_robot_state(
1555
+ self._build_robot_state_row(observation)
1556
+ )
1557
+ self._episode_writer.write_force_torque(
1558
+ self._build_force_torque_row(observation)
1559
+ )
1560
+ self._episode_writer.write_cv_output(self._build_cv_output_row(observation))
1561
+
1562
+ def _phase_to_failure_phase(self, phase: str | None) -> str:
1563
+ phase_key = (phase or "").upper()
1564
+ return {
1565
+ "APPROACH": "approach",
1566
+ "ALIGN": "alignment",
1567
+ "GUARDED_INSERT": "insertion",
1568
+ "RETRY_OR_FINISH": "recovery",
1569
+ }.get(phase_key, "termination")
1570
+
1571
+ def _classify_failure(
1572
+ self,
1573
+ *,
1574
+ wrapper_returned_success: bool,
1575
+ termination_reason: str | None,
1576
+ observation: dict[str, Any] | None,
1577
+ action_result: dict[str, Any] | None,
1578
+ ) -> tuple[str, str, bool]:
1579
+ insertion_event_detected = bool(self._insertion_event_seen)
1580
+ if wrapper_returned_success and insertion_event_detected:
1581
+ return "none", "none", False
1582
+
1583
+ invalid_reason = None if observation is None else observation.get("invalid_reason")
1584
+ phase = None
1585
+ if action_result is not None:
1586
+ phase = action_result.get("phase_after") or action_result.get("phase_before")
1587
+ failure_phase = self._phase_to_failure_phase(phase)
1588
+
1589
+ if invalid_reason == "stale_cv_output":
1590
+ return "stale_cv_output", "perception", True
1591
+ if invalid_reason == "stale_robot_state":
1592
+ return "timestamp_mismatch", "termination", False
1593
+ if invalid_reason == "non_finite_state":
1594
+ return "wrapper_exception", "termination", False
1595
+ if action_result is not None and not bool(action_result.get("action_accepted", True)):
1596
+ return "wrapper_exception", failure_phase, False
1597
+
1598
+ reason = termination_reason or ""
1599
+ if reason == "force_stop":
1600
+ return "excessive_force", "contact", True
1601
+ if reason in {"no_progress", "timeout", "guarded_insert_complete"}:
1602
+ return "no_progress", failure_phase, True
1603
+ if reason == "retry_budget_exhausted":
1604
+ return "late_recovery", "recovery", True
1605
+ if reason == "retry_missing_target":
1606
+ return "wrapper_exception", "recovery", False
1607
+
1608
+ return "premature_termination", failure_phase, False
1609
+
1610
+ def _write_action_and_wrapper_output(
1611
+ self,
1612
+ *,
1613
+ observation: dict[str, Any],
1614
+ action_result: dict[str, Any],
1615
+ ) -> None:
1616
+ self._previous_action_record = {
1617
+ "timestamp": action_result.get("timestamp"),
1618
+ "action_id": action_result.get("action_id"),
1619
+ "action_type": action_result.get("action_type"),
1620
+ "action_accepted": action_result.get("action_accepted"),
1621
+ "action_clipped": action_result.get("action_clipped"),
1622
+ "phase_after": action_result.get("phase_after"),
1623
+ "termination_reason": action_result.get("termination_reason"),
1624
+ "policy_route": self._active_policy_route,
1625
+ }
1626
+ self._episode_last_action_result = dict(action_result)
1627
+
1628
+ wrapper_output = {
1629
+ "timestamp": action_result.get("timestamp", observation["timestamp"]),
1630
+ "wrapper_valid": bool(observation["wrapper_valid"]),
1631
+ "invalid_reason": observation.get("invalid_reason"),
1632
+ "cv_stale": bool(observation.get("cv_stale", False)),
1633
+ "cv_latency_ms": observation.get("cv_latency_ms"),
1634
+ "robot_state_latency_ms": observation.get("robot_state_latency_ms"),
1635
+ "force_latency_ms": observation.get("force_latency_ms"),
1636
+ "action_accepted": bool(action_result.get("action_accepted", False)),
1637
+ "action_clipped": bool(action_result.get("action_clipped", False)),
1638
+ "policy_name": self._canonical_policy_name(),
1639
+ "checkpoint": self.checkpoint_name,
1640
+ "checkpoint_route": self._active_policy_route,
1641
+ "phase": action_result.get("phase_after")
1642
+ or action_result.get("phase_before")
1643
+ or observation.get("policy_phase"),
1644
+ "termination_reason": action_result.get("termination_reason"),
1645
+ "force_n": action_result.get("force_n"),
1646
+ "max_force_n": action_result.get("max_force_n"),
1647
+ "insertion_event_seen": bool(self._insertion_event_seen),
1648
+ "wrapper_returned_success": action_result.get("wrapper_returned_success"),
1649
+ "guidance_summary": action_result.get("guidance_summary"),
1650
+ }
1651
+ if "plug_port_geometry" in observation:
1652
+ wrapper_output["plug_port_geometry"] = observation.get(
1653
+ "plug_port_geometry"
1654
+ )
1655
+ for optional_key in (
1656
+ "guidance_mode",
1657
+ "guidance_advisory_only",
1658
+ "guidance_applied",
1659
+ "guidance_would_apply",
1660
+ "guidance_ready_for_align",
1661
+ "guidance_ready_for_insert",
1662
+ "guidance_proposed_local_offset_m",
1663
+ "guidance_proposed_world_offset_m",
1664
+ "terminal_strategy",
1665
+ "supervisor_phase",
1666
+ "primitive_branch",
1667
+ "primitive_template",
1668
+ "primitive_name",
1669
+ "primitive_phase",
1670
+ "primitive_runtime_enabled",
1671
+ "primitive_transition_index",
1672
+ ):
1673
+ if optional_key in action_result:
1674
+ wrapper_output[optional_key] = action_result.get(optional_key)
1675
+ for optional_key in (
1676
+ "hybrid_controller",
1677
+ "hybrid_mode",
1678
+ "hybrid_handoff_reached",
1679
+ "hybrid_handoff_step",
1680
+ "hybrid_handoff_reason",
1681
+ "hybrid_handoff_timestamp_s",
1682
+ "hybrid_insertion_policy_name",
1683
+ "hybrid_insertion_checkpoint",
1684
+ ):
1685
+ if optional_key in action_result:
1686
+ wrapper_output[optional_key] = action_result.get(optional_key)
1687
+ self._episode_last_wrapper_output = wrapper_output
1688
+
1689
+ if self._episode_writer is None:
1690
+ return
1691
+ self._episode_writer.write_action(action_result)
1692
+ self._episode_writer.write_wrapper_output(wrapper_output)
1693
+
1694
+ def _finalize_canonical_episode(
1695
+ self,
1696
+ *,
1697
+ wrapper_returned_success: bool,
1698
+ termination_reason: str,
1699
+ ) -> None:
1700
+ self._log_generic_runtime_geometry_diagnostics(
1701
+ wrapper_returned_success=wrapper_returned_success,
1702
+ termination_reason=termination_reason,
1703
+ )
1704
+ if self._episode_writer is None:
1705
+ return
1706
+
1707
+ success = bool(wrapper_returned_success and self._insertion_event_seen)
1708
+ failure_type, failure_phase, recoverable = self._classify_failure(
1709
+ wrapper_returned_success=wrapper_returned_success,
1710
+ termination_reason=termination_reason,
1711
+ observation=self._last_policy_observation,
1712
+ action_result=self._episode_last_action_result,
1713
+ )
1714
+ labels = {
1715
+ "success": success,
1716
+ "failure_type": failure_type,
1717
+ "failure_phase": failure_phase,
1718
+ "recoverable": recoverable,
1719
+ "termination_reason": termination_reason,
1720
+ "wrapper_returned_success": wrapper_returned_success,
1721
+ "insertion_event_detected": bool(self._insertion_event_seen),
1722
+ }
1723
+ metrics = {
1724
+ "checkpoint": self.checkpoint_name,
1725
+ "checkpoint_route": self._active_policy_route,
1726
+ "policy_name": self._canonical_policy_name(),
1727
+ "max_force_n": self._episode_last_wrapper_output.get("max_force_n")
1728
+ if self._episode_last_wrapper_output
1729
+ else None,
1730
+ }
1731
+ self._episode_writer.finalize(labels=labels, metrics=metrics)
1732
+ self._episode_writer = None
1733
+
1734
+ def step(self, action: np.ndarray) -> dict[str, Any]:
1735
+ if self._active_observation_msg is None:
1736
+ raise RuntimeError("No active observation is available for wrapper step().")
1737
+ if self._active_move_robot is None:
1738
+ raise RuntimeError("No active move_robot callback is available for step().")
1739
+
1740
+ if action.shape[0] < 6:
1741
+ raise RuntimeError(
1742
+ f"ACT action has unexpected shape {action.shape}; need at least 6 dims"
1743
+ )
1744
+
1745
+ timestamp = self._clock_now_seconds()
1746
+ action_id = self._episode_action_id
1747
+ self._episode_action_id += 1
1748
+ motion_update = None
1749
+ action_type = "cartesian_delta"
1750
+ action_clipped = False
1751
+ action_accepted = False
1752
+ pose_target_position = (
1753
+ action[6:9].astype(float).tolist() if action.shape[0] >= 9 else None
1754
+ )
1755
+ pose_target_quaternion = None
1756
+
1757
+ if self.command_mode == "pose" and action.shape[0] >= 13:
1758
+ quat = np.array(action[9:13], dtype=np.float64)
1759
+ quat_norm = float(np.linalg.norm(quat))
1760
+ quat = (
1761
+ np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
1762
+ if quat_norm < 1e-8
1763
+ else quat / quat_norm
1764
+ )
1765
+ pose_target_quaternion = quat.astype(float).tolist()
1766
+ pose = Pose(
1767
+ position=Point(
1768
+ x=float(action[6]),
1769
+ y=float(action[7]),
1770
+ z=float(action[8]),
1771
+ ),
1772
+ orientation=Quaternion(
1773
+ x=float(quat[0]),
1774
+ y=float(quat[1]),
1775
+ z=float(quat[2]),
1776
+ w=float(quat[3]),
1777
+ ),
1778
+ )
1779
+ motion_update = self.create_pose_motion_update(pose)
1780
+ action_type = "pose_target"
1781
+ else:
1782
+ twist = Twist(
1783
+ linear=Vector3(
1784
+ x=float(action[0]), y=float(action[1]), z=float(action[2])
1785
+ ),
1786
+ angular=Vector3(
1787
+ x=float(action[3]), y=float(action[4]), z=float(action[5])
1788
+ ),
1789
+ )
1790
+ motion_update = self.set_cartesian_twist_target(twist)
1791
+ action_type = "cartesian_delta"
1792
+
1793
+ action_accepted = bool(self._active_move_robot(motion_update=motion_update))
1794
+ return {
1795
+ "timestamp": timestamp,
1796
+ "action_id": action_id,
1797
+ "source": self._episode_source,
1798
+ "policy_route": self._active_policy_route,
1799
+ "action_type": action_type,
1800
+ "raw_action": action.astype(float).tolist(),
1801
+ "raw_linear": action[:3].astype(float).tolist(),
1802
+ "raw_angular": action[3:6].astype(float).tolist(),
1803
+ "pose_target_position": pose_target_position,
1804
+ "pose_target_quaternion": pose_target_quaternion,
1805
+ "joint_target_norm": float(
1806
+ np.linalg.norm(action[13:19]) if action.shape[0] >= 19 else 0.0
1807
+ ),
1808
+ "action_accepted": action_accepted,
1809
+ "action_clipped": action_clipped,
1810
+ "phase_before": getattr(self, "_phase", None),
1811
+ "phase_after": getattr(self, "_phase", None),
1812
+ "termination_reason": None,
1813
+ "wrapper_returned_success": None,
1814
+ "force_n": None,
1815
+ "max_force_n": None,
1816
+ "is_recovery": False,
1817
+ "feedback": "in progress...",
1818
+ }
1819
+
1820
+ def prepare_observations(
1821
+ self, obs_msg: Observation, task_msg: Task | None
1822
+ ) -> Dict[str, torch.Tensor]:
1823
+ """Convert ROS Observation message into dictionary of normalized tensors."""
1824
+
1825
+ # --- Process Cameras ---
1826
+ obs = {
1827
+ "observation.images.left_camera": self._img_to_tensor(
1828
+ obs_msg.left_image,
1829
+ self.device,
1830
+ self.image_scaling,
1831
+ self.img_stats["left"]["mean"],
1832
+ self.img_stats["left"]["std"],
1833
+ ),
1834
+ "observation.images.center_camera": self._img_to_tensor(
1835
+ obs_msg.center_image,
1836
+ self.device,
1837
+ self.image_scaling,
1838
+ self.img_stats["center"]["mean"],
1839
+ self.img_stats["center"]["std"],
1840
+ ),
1841
+ "observation.images.right_camera": self._img_to_tensor(
1842
+ obs_msg.right_image,
1843
+ self.device,
1844
+ self.image_scaling,
1845
+ self.img_stats["right"]["mean"],
1846
+ self.img_stats["right"]["std"],
1847
+ ),
1848
+ }
1849
+
1850
+ # --- Process Robot State ---
1851
+ # Construct flat state vector (48 dims) matching the recorder/training order.
1852
+ state_np = self._build_raw_state_vector(obs_msg, task_msg)
1853
+
1854
+ # Normalize State
1855
+ raw_state_tensor = (
1856
+ torch.from_numpy(state_np).float().unsqueeze(0).to(self.device)
1857
+ )
1858
+ if not np.isfinite(state_np).all():
1859
+ bad_count = int(np.size(state_np) - np.isfinite(state_np).sum())
1860
+ self.get_logger().warning(
1861
+ f"Non-finite raw state values detected: {bad_count}. Replacing with zeros."
1862
+ )
1863
+ raw_state_tensor = torch.from_numpy(
1864
+ np.nan_to_num(state_np, nan=0.0, posinf=0.0, neginf=0.0)
1865
+ ).float().unsqueeze(0).to(self.device)
1866
+ obs["observation.state"] = (raw_state_tensor - self.state_mean) / self.state_std
1867
+ if not torch.isfinite(obs["observation.state"]).all():
1868
+ bad_count = int((~torch.isfinite(obs["observation.state"])).sum().item())
1869
+ self.get_logger().warning(
1870
+ f"Non-finite normalized state values detected: {bad_count}. Replacing with zeros."
1871
+ )
1872
+ obs["observation.state"] = torch.nan_to_num(obs["observation.state"])
1873
+
1874
+ return obs
1875
+
1876
+ def insert_cable(
1877
+ self,
1878
+ task: Task,
1879
+ get_observation: GetObservationCallback,
1880
+ move_robot: MoveRobotCallback,
1881
+ send_feedback: SendFeedbackCallback,
1882
+ **kwargs,
1883
+ ):
1884
+ self._activate_policy_bundle_for_task(task)
1885
+ self.policy.reset()
1886
+ self._begin_canonical_episode(task)
1887
+ self.get_logger().info(f"RunACT.insert_cable() enter. Task: {task}")
1888
+
1889
+ start_time = time.time()
1890
+ inference_count = 0
1891
+
1892
+ # Run inference for 30 seconds
1893
+ while time.time() - start_time < 30.0:
1894
+ loop_start = time.time()
1895
+
1896
+ # 1. Get & Process Observation
1897
+ observation_msg = get_observation()
1898
+
1899
+ if observation_msg is None:
1900
+ self.get_logger().info("No observation received.")
1901
+ continue
1902
+
1903
+ self._set_active_runtime_context(
1904
+ observation_msg=observation_msg,
1905
+ task_msg=task,
1906
+ move_robot=move_robot,
1907
+ )
1908
+ policy_observation = self.get_policy_observation()
1909
+ self._write_policy_observation(policy_observation)
1910
+
1911
+ obs_tensors = self.prepare_observations(observation_msg, task)
1912
+
1913
+ # 2. Model Inference
1914
+ with torch.inference_mode():
1915
+ normalized_action = self.policy.select_action(obs_tensors)
1916
+ if not torch.isfinite(normalized_action).all():
1917
+ bad_count = int((~torch.isfinite(normalized_action)).sum().item())
1918
+ self.get_logger().warning(
1919
+ f"Non-finite normalized ACT action detected: {bad_count}. Replacing with zeros."
1920
+ )
1921
+ normalized_action = torch.nan_to_num(normalized_action)
1922
+
1923
+ # 3. Un-normalize Action
1924
+ # Formula: (norm * std) + mean
1925
+ raw_action_tensor = (normalized_action * self.action_std) + self.action_mean
1926
+
1927
+ # 4. Extract and command. For the Quantarune ACT checkpoint, the action
1928
+ # layout is:
1929
+ # [0:3] Cartesian linear twist
1930
+ # [3:6] Cartesian angular twist
1931
+ # [6:13] Cartesian target pose
1932
+ # [13:19] Joint velocity targets
1933
+ action = raw_action_tensor[0].detach().cpu().numpy()
1934
+ if not np.isfinite(action).all():
1935
+ bad_count = int(np.size(action) - np.isfinite(action).sum())
1936
+ self.get_logger().warning(
1937
+ f"Non-finite unnormalized ACT action detected: {bad_count}. Replacing with zeros."
1938
+ )
1939
+ action = np.nan_to_num(action, nan=0.0, posinf=0.0, neginf=0.0)
1940
+
1941
+ if (
1942
+ self.log_every_n_steps > 0
1943
+ and inference_count % self.log_every_n_steps == 0
1944
+ ):
1945
+ linear = action[:3]
1946
+ angular = action[3:6]
1947
+ pose_position = action[6:9] if action.shape[0] >= 9 else np.zeros(3)
1948
+ joint_targets = (
1949
+ action[13:19] if action.shape[0] >= 19 else np.zeros(6)
1950
+ )
1951
+ self.get_logger().info(
1952
+ "ACT action "
1953
+ f"step={inference_count + 1} "
1954
+ f"linear={linear.tolist()} "
1955
+ f"linear_norm={float(np.linalg.norm(linear)):.6f} "
1956
+ f"angular={angular.tolist()} "
1957
+ f"angular_norm={float(np.linalg.norm(angular)):.6f} "
1958
+ f"pose_position={pose_position.tolist()} "
1959
+ f"joint_norm={float(np.linalg.norm(joint_targets)):.6f}"
1960
+ )
1961
+
1962
+ action_result = self.step(action)
1963
+ self._write_action_and_wrapper_output(
1964
+ observation=policy_observation,
1965
+ action_result=action_result,
1966
+ )
1967
+ send_feedback(str(action_result.get("feedback", "in progress...")))
1968
+ inference_count += 1
1969
+
1970
+ # Maintain control rate (approx 4Hz loop = 0.25s sleep)
1971
+ elapsed = time.time() - loop_start
1972
+ time.sleep(max(0, 0.25 - elapsed))
1973
+
1974
+ self.get_logger().info("RunACT.insert_cable() exiting...")
1975
+ self._finalize_canonical_episode(
1976
+ wrapper_returned_success=True,
1977
+ termination_reason="timeout",
1978
+ )
1979
+ return True
1980
+
1981
+ def set_cartesian_twist_target(self, twist: Twist, frame_id: str = "base_link"):
1982
+ motion_update_msg = MotionUpdate()
1983
+ motion_update_msg.velocity = twist
1984
+ motion_update_msg.header.frame_id = frame_id
1985
+ motion_update_msg.header.stamp = self.get_clock().now().to_msg()
1986
+
1987
+ motion_update_msg.target_stiffness = np.diag(
1988
+ [100.0, 100.0, 100.0, 50.0, 50.0, 50.0]
1989
+ ).flatten()
1990
+ motion_update_msg.target_damping = np.diag(
1991
+ [40.0, 40.0, 40.0, 15.0, 15.0, 15.0]
1992
+ ).flatten()
1993
+
1994
+ motion_update_msg.feedforward_wrench_at_tip = Wrench(
1995
+ force=Vector3(x=0.0, y=0.0, z=0.0), torque=Vector3(x=0.0, y=0.0, z=0.0)
1996
+ )
1997
+
1998
+ motion_update_msg.wrench_feedback_gains_at_tip = [0.5, 0.5, 0.5, 0.0, 0.0, 0.0]
1999
+
2000
+ motion_update_msg.trajectory_generation_mode.mode = (
2001
+ TrajectoryGenerationMode.MODE_VELOCITY
2002
+ )
2003
+
2004
+ return motion_update_msg
2005
+
2006
+ def create_pose_motion_update(self, pose: Pose, frame_id: str = "base_link"):
2007
+ motion_update_msg = MotionUpdate()
2008
+ motion_update_msg.pose = pose
2009
+ motion_update_msg.header.frame_id = frame_id
2010
+ motion_update_msg.header.stamp = self.get_clock().now().to_msg()
2011
+
2012
+ motion_update_msg.target_stiffness = np.diag(
2013
+ [90.0, 90.0, 90.0, 50.0, 50.0, 50.0]
2014
+ ).flatten()
2015
+ motion_update_msg.target_damping = np.diag(
2016
+ [50.0, 50.0, 50.0, 20.0, 20.0, 20.0]
2017
+ ).flatten()
2018
+
2019
+ motion_update_msg.feedforward_wrench_at_tip = Wrench(
2020
+ force=Vector3(x=0.0, y=0.0, z=0.0), torque=Vector3(x=0.0, y=0.0, z=0.0)
2021
+ )
2022
+ motion_update_msg.wrench_feedback_gains_at_tip = [0.5, 0.5, 0.5, 0.0, 0.0, 0.0]
2023
+ motion_update_msg.trajectory_generation_mode.mode = (
2024
+ TrajectoryGenerationMode.MODE_POSITION
2025
+ )
2026
+
2027
+ return motion_update_msg
policy/aic_example_policies/ros/RunACTCompetitor.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2026 Intrinsic Innovation LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import time
21
+ from typing import Sequence
22
+
23
+ import numpy as np
24
+ import torch
25
+ from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3, Wrench, WrenchStamped
26
+ from std_msgs.msg import String
27
+
28
+ from aic_control_interfaces.msg import MotionUpdate, TrajectoryGenerationMode
29
+ from aic_model.policy import GetObservationCallback, MoveRobotCallback, SendFeedbackCallback
30
+ from aic_task_interfaces.msg import Task
31
+
32
+ from .RunACT import RunACT
33
+
34
+
35
+ def _parse_float(name: str, default: float) -> float:
36
+ value = os.environ.get(name)
37
+ return float(value) if value is not None else default
38
+
39
+
40
+ def _parse_float_list(name: str, default: Sequence[float]) -> list[float]:
41
+ value = os.environ.get(name)
42
+ if value is None:
43
+ return list(default)
44
+ parsed = [float(part.strip()) for part in value.split(",") if part.strip()]
45
+ if len(parsed) != len(default):
46
+ raise ValueError(
47
+ f"{name} expected {len(default)} comma-separated floats, got {len(parsed)}"
48
+ )
49
+ return parsed
50
+
51
+
52
+ def _parse_bool(name: str, default: bool) -> bool:
53
+ value = os.environ.get(name)
54
+ if value is None:
55
+ return default
56
+ return value.strip().lower() in {"1", "true", "yes", "on"}
57
+
58
+
59
+ class RunACTCompetitor(RunACT):
60
+ """Experimental ACT runtime with force-shaped competitor-style descent logic."""
61
+
62
+ def __init__(self, parent_node):
63
+ super().__init__(parent_node)
64
+ # Preserve the base ACT mode resolution by default. The newer 19-D
65
+ # checkpoint drives meaningful motion through the pose slice, so
66
+ # forcing twist mode collapses the policy into near-zero commands.
67
+ self._command_mode_preference = os.environ.get(
68
+ "AIC_ACT_COMPETITOR_COMMAND_MODE", self._command_mode_preference
69
+ )
70
+ self.command_mode = self._resolve_bundle_command_mode(self.action_dim)
71
+ self.max_linear_speed_mps = _parse_float(
72
+ "AIC_ACT_COMPETITOR_MAX_LINEAR_SPEED_MPS", 0.06
73
+ )
74
+ self.max_angular_speed_rps = _parse_float(
75
+ "AIC_ACT_COMPETITOR_MAX_ANGULAR_SPEED_RPS", 0.5
76
+ )
77
+ self.force_rampdown_start_n = _parse_float(
78
+ "AIC_ACT_COMPETITOR_FORCE_RAMPDOWN_START_N", 12.0
79
+ )
80
+ self.force_rampdown_full_n = _parse_float(
81
+ "AIC_ACT_COMPETITOR_FORCE_RAMPDOWN_FULL_N", 18.0
82
+ )
83
+ self.force_hard_stop_n = _parse_float(
84
+ "AIC_ACT_COMPETITOR_FORCE_HARD_STOP_N", 19.0
85
+ )
86
+ self.control_stiffness_diag = _parse_float_list(
87
+ "AIC_ACT_COMPETITOR_STIFFNESS_DIAG",
88
+ [85.0, 85.0, 85.0, 85.0, 85.0, 85.0],
89
+ )
90
+ self.control_damping_diag = _parse_float_list(
91
+ "AIC_ACT_COMPETITOR_DAMPING_DIAG",
92
+ [75.0, 75.0, 75.0, 75.0, 75.0, 75.0],
93
+ )
94
+ self.contact_wrench_feedback_gains = _parse_float_list(
95
+ "AIC_ACT_COMPETITOR_CONTACT_GAINS",
96
+ [0.5, 0.5, 0.5, 0.0, 0.0, 0.0],
97
+ )
98
+ self.base_wrench_feedback_gains = _parse_float_list(
99
+ "AIC_ACT_COMPETITOR_BASE_GAINS",
100
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
101
+ )
102
+ self.control_period_s = _parse_float(
103
+ "AIC_ACT_COMPETITOR_CONTROL_PERIOD_S", 0.25
104
+ )
105
+ self.require_insertion_event = _parse_bool(
106
+ "AIC_ACT_COMPETITOR_REQUIRE_INSERTION_EVENT", False
107
+ )
108
+
109
+ self._latest_wrench_msg: WrenchStamped | None = None
110
+ self._insertion_event_seen = False
111
+ self._last_insertion_event = ""
112
+ self._wrench_sub = self._parent_node.create_subscription(
113
+ WrenchStamped, "/fts_broadcaster/wrench", self._wrench_callback, 10
114
+ )
115
+ self._insertion_event_sub = self._parent_node.create_subscription(
116
+ String, "/scoring/insertion_event", self._insertion_event_callback, 10
117
+ )
118
+ self.get_logger().info(
119
+ "RunACTCompetitor active with "
120
+ f"command_mode={self.command_mode} "
121
+ f"max_linear={self.max_linear_speed_mps:.3f} "
122
+ f"max_angular={self.max_angular_speed_rps:.3f} "
123
+ f"control_period_s={self.control_period_s:.3f} "
124
+ f"require_insertion_event={self.require_insertion_event} "
125
+ f"base_gains={self.base_wrench_feedback_gains} "
126
+ f"contact_gains={self.contact_wrench_feedback_gains} "
127
+ f"force_thresholds=({self.force_rampdown_start_n:.1f}, "
128
+ f"{self.force_rampdown_full_n:.1f}, {self.force_hard_stop_n:.1f})"
129
+ )
130
+
131
+ def _wrench_callback(self, msg: WrenchStamped) -> None:
132
+ self._latest_wrench_msg = msg
133
+
134
+ def _insertion_event_callback(self, msg: String) -> None:
135
+ self._insertion_event_seen = True
136
+ self._last_insertion_event = msg.data
137
+
138
+ @staticmethod
139
+ def _clip_vector_norm(vector: np.ndarray, limit: float) -> np.ndarray:
140
+ norm = float(np.linalg.norm(vector))
141
+ if norm <= limit or norm <= 1e-9:
142
+ return vector
143
+ return vector * (limit / norm)
144
+
145
+ def _compensated_force_magnitude(self, observation_msg) -> float | None:
146
+ if self._latest_wrench_msg is None:
147
+ return None
148
+
149
+ tare_wrench = observation_msg.controller_state.fts_tare_offset.wrench
150
+ force = np.array(
151
+ [
152
+ float(self._latest_wrench_msg.wrench.force.x - tare_wrench.force.x),
153
+ float(self._latest_wrench_msg.wrench.force.y - tare_wrench.force.y),
154
+ float(self._latest_wrench_msg.wrench.force.z - tare_wrench.force.z),
155
+ ],
156
+ dtype=np.float64,
157
+ )
158
+ return float(np.linalg.norm(force))
159
+
160
+ def _shape_twist(
161
+ self, twist: Twist, observation_msg
162
+ ) -> tuple[Twist, list[float], float | None]:
163
+ linear = np.array(
164
+ [twist.linear.x, twist.linear.y, twist.linear.z], dtype=np.float64
165
+ )
166
+ angular = np.array(
167
+ [twist.angular.x, twist.angular.y, twist.angular.z], dtype=np.float64
168
+ )
169
+
170
+ linear = self._clip_vector_norm(linear, self.max_linear_speed_mps)
171
+ angular = self._clip_vector_norm(angular, self.max_angular_speed_rps)
172
+
173
+ wrench_feedback_gains = self.base_wrench_feedback_gains.copy()
174
+ force_mag = self._compensated_force_magnitude(observation_msg)
175
+ if force_mag is not None:
176
+ if force_mag >= self.force_hard_stop_n:
177
+ linear[:] = 0.0
178
+ angular[:] = 0.0
179
+ wrench_feedback_gains = self.contact_wrench_feedback_gains.copy()
180
+ elif force_mag > self.force_rampdown_start_n:
181
+ ramp_span = max(
182
+ self.force_rampdown_full_n - self.force_rampdown_start_n, 1e-6
183
+ )
184
+ force_scale = 1.0 - (
185
+ (force_mag - self.force_rampdown_start_n) / ramp_span
186
+ )
187
+ linear *= float(np.clip(force_scale, 0.0, 1.0))
188
+ wrench_feedback_gains = self.contact_wrench_feedback_gains.copy()
189
+
190
+ shaped_twist = Twist(
191
+ linear=Vector3(
192
+ x=float(linear[0]), y=float(linear[1]), z=float(linear[2])
193
+ ),
194
+ angular=Vector3(
195
+ x=float(angular[0]), y=float(angular[1]), z=float(angular[2])
196
+ ),
197
+ )
198
+ return shaped_twist, wrench_feedback_gains, force_mag
199
+
200
+ def _shape_pose(
201
+ self, pose: Pose, observation_msg
202
+ ) -> tuple[Pose, list[float], float | None]:
203
+ shaped_pose = Pose(
204
+ position=Point(
205
+ x=float(pose.position.x),
206
+ y=float(pose.position.y),
207
+ z=float(pose.position.z),
208
+ ),
209
+ orientation=Quaternion(
210
+ x=float(pose.orientation.x),
211
+ y=float(pose.orientation.y),
212
+ z=float(pose.orientation.z),
213
+ w=float(pose.orientation.w),
214
+ ),
215
+ )
216
+
217
+ wrench_feedback_gains = self.base_wrench_feedback_gains.copy()
218
+ force_mag = self._compensated_force_magnitude(observation_msg)
219
+ if force_mag is None:
220
+ return shaped_pose, wrench_feedback_gains, force_mag
221
+ current_pose = observation_msg.controller_state.tcp_pose
222
+ current_pos = np.array(
223
+ [
224
+ float(current_pose.position.x),
225
+ float(current_pose.position.y),
226
+ float(current_pose.position.z),
227
+ ],
228
+ dtype=np.float64,
229
+ )
230
+ target_pos = np.array(
231
+ [
232
+ float(shaped_pose.position.x),
233
+ float(shaped_pose.position.y),
234
+ float(shaped_pose.position.z),
235
+ ],
236
+ dtype=np.float64,
237
+ )
238
+
239
+ if force_mag >= self.force_hard_stop_n:
240
+ shaped_pose.position = Point(
241
+ x=float(current_pos[0]),
242
+ y=float(current_pos[1]),
243
+ z=float(current_pos[2]),
244
+ )
245
+ shaped_pose.orientation = current_pose.orientation
246
+ wrench_feedback_gains = self.contact_wrench_feedback_gains.copy()
247
+ elif force_mag > self.force_rampdown_start_n:
248
+ ramp_span = max(
249
+ self.force_rampdown_full_n - self.force_rampdown_start_n, 1e-6
250
+ )
251
+ force_scale = 1.0 - (
252
+ (force_mag - self.force_rampdown_start_n) / ramp_span
253
+ )
254
+ force_scale = float(np.clip(force_scale, 0.0, 1.0))
255
+ shaped_pos = current_pos + force_scale * (target_pos - current_pos)
256
+ shaped_pose.position = Point(
257
+ x=float(shaped_pos[0]),
258
+ y=float(shaped_pos[1]),
259
+ z=float(shaped_pos[2]),
260
+ )
261
+ wrench_feedback_gains = self.contact_wrench_feedback_gains.copy()
262
+
263
+ return shaped_pose, wrench_feedback_gains, force_mag
264
+
265
+ def insert_cable(
266
+ self,
267
+ task: Task,
268
+ get_observation: GetObservationCallback,
269
+ move_robot: MoveRobotCallback,
270
+ send_feedback: SendFeedbackCallback,
271
+ **kwargs,
272
+ ):
273
+ self._activate_policy_bundle_for_task(task)
274
+ self.policy.reset()
275
+ self._insertion_event_seen = False
276
+ self._last_insertion_event = ""
277
+ self.get_logger().info(f"RunACTCompetitor.insert_cable() enter. Task: {task}")
278
+
279
+ start_time = time.time()
280
+ inference_count = 0
281
+
282
+ while time.time() - start_time < 30.0:
283
+ if self._insertion_event_seen:
284
+ self.get_logger().info(
285
+ f"Insertion event observed; exiting success. event={self._last_insertion_event!r}"
286
+ )
287
+ return True
288
+
289
+ loop_start = time.time()
290
+ observation_msg = get_observation()
291
+ if observation_msg is None:
292
+ self.get_logger().info("No observation received.")
293
+ continue
294
+
295
+ obs_tensors = self.prepare_observations(observation_msg, task)
296
+
297
+ with torch.inference_mode():
298
+ normalized_action = self.policy.select_action(obs_tensors)
299
+
300
+ if not torch.isfinite(normalized_action).all():
301
+ bad_count = int((~torch.isfinite(normalized_action)).sum().item())
302
+ self.get_logger().warning(
303
+ f"Non-finite normalized ACT action detected: {bad_count}. Replacing with zeros."
304
+ )
305
+ normalized_action = torch.nan_to_num(normalized_action)
306
+
307
+ raw_action_tensor = (normalized_action * self.action_std) + self.action_mean
308
+ action = raw_action_tensor[0].detach().cpu().numpy()
309
+ if not np.isfinite(action).all():
310
+ bad_count = int(np.size(action) - np.isfinite(action).sum())
311
+ self.get_logger().warning(
312
+ f"Non-finite unnormalized ACT action detected: {bad_count}. Replacing with zeros."
313
+ )
314
+ action = np.nan_to_num(action, nan=0.0, posinf=0.0, neginf=0.0)
315
+ if action.shape[0] < 6:
316
+ raise RuntimeError(
317
+ f"ACT action has unexpected shape {action.shape}; need at least 6 dims"
318
+ )
319
+
320
+ pose_position = action[6:9] if action.shape[0] >= 9 else np.zeros(3)
321
+ joint_targets = action[13:19] if action.shape[0] >= 19 else np.zeros(6)
322
+ shaped_linear_log = [float("nan")] * 3
323
+ shaped_angular_log = [float("nan")] * 3
324
+ shaped_pose_position_log = [float("nan")] * 3
325
+
326
+ if self.command_mode == "pose" and action.shape[0] >= 13:
327
+ quat = np.array(action[9:13], dtype=np.float64)
328
+ quat_norm = float(np.linalg.norm(quat))
329
+ if quat_norm < 1e-8:
330
+ quat = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
331
+ else:
332
+ quat = quat / quat_norm
333
+
334
+ pose = Pose(
335
+ position=Point(
336
+ x=float(action[6]),
337
+ y=float(action[7]),
338
+ z=float(action[8]),
339
+ ),
340
+ orientation=Quaternion(
341
+ x=float(quat[0]),
342
+ y=float(quat[1]),
343
+ z=float(quat[2]),
344
+ w=float(quat[3]),
345
+ ),
346
+ )
347
+ (
348
+ shaped_pose,
349
+ wrench_feedback_gains,
350
+ compensated_force_n,
351
+ ) = self._shape_pose(pose, observation_msg)
352
+ shaped_pose_position_log = [
353
+ float(shaped_pose.position.x),
354
+ float(shaped_pose.position.y),
355
+ float(shaped_pose.position.z),
356
+ ]
357
+ move_robot(
358
+ motion_update=self.create_pose_motion_update(
359
+ shaped_pose,
360
+ wrench_feedback_gains=wrench_feedback_gains,
361
+ )
362
+ )
363
+ else:
364
+ twist = Twist(
365
+ linear=Vector3(
366
+ x=float(action[0]), y=float(action[1]), z=float(action[2])
367
+ ),
368
+ angular=Vector3(
369
+ x=float(action[3]), y=float(action[4]), z=float(action[5])
370
+ ),
371
+ )
372
+ (
373
+ shaped_twist,
374
+ wrench_feedback_gains,
375
+ compensated_force_n,
376
+ ) = self._shape_twist(twist, observation_msg)
377
+ shaped_linear_log = [
378
+ float(shaped_twist.linear.x),
379
+ float(shaped_twist.linear.y),
380
+ float(shaped_twist.linear.z),
381
+ ]
382
+ shaped_angular_log = [
383
+ float(shaped_twist.angular.x),
384
+ float(shaped_twist.angular.y),
385
+ float(shaped_twist.angular.z),
386
+ ]
387
+
388
+ motion_update = self.set_cartesian_twist_target(
389
+ shaped_twist,
390
+ wrench_feedback_gains=wrench_feedback_gains,
391
+ )
392
+ move_robot(motion_update=motion_update)
393
+
394
+ if self.log_every_n_steps > 0 and inference_count % self.log_every_n_steps == 0:
395
+ self.get_logger().info(
396
+ "ACT competitor action "
397
+ f"step={inference_count + 1} "
398
+ f"raw_linear={[float(action[i]) for i in range(3)]} "
399
+ f"raw_angular={[float(action[i]) for i in range(3, 6)]} "
400
+ f"shaped_linear={shaped_linear_log} "
401
+ f"shaped_angular={shaped_angular_log} "
402
+ f"pose_position={pose_position.tolist()} "
403
+ f"shaped_pose_position={shaped_pose_position_log} "
404
+ f"joint_norm={float(np.linalg.norm(joint_targets)):.6f} "
405
+ f"mode={self.command_mode} "
406
+ f"force_n={compensated_force_n if compensated_force_n is not None else float('nan'):.4f} "
407
+ f"gains={wrench_feedback_gains}"
408
+ )
409
+
410
+ feedback = "in progress..."
411
+ if compensated_force_n is not None:
412
+ feedback = f"in progress... force={compensated_force_n:.2f}N"
413
+ send_feedback(feedback)
414
+ inference_count += 1
415
+
416
+ elapsed = time.time() - loop_start
417
+ time.sleep(max(0.0, self.control_period_s - elapsed))
418
+
419
+ self.get_logger().info(
420
+ "RunACTCompetitor.insert_cable() exiting without insertion event."
421
+ )
422
+ return True if not self.require_insertion_event else self._insertion_event_seen
423
+
424
+ def create_pose_motion_update(
425
+ self,
426
+ pose: Pose,
427
+ frame_id: str = "base_link",
428
+ wrench_feedback_gains: Sequence[float] | None = None,
429
+ ):
430
+ motion_update_msg = MotionUpdate()
431
+ motion_update_msg.pose = pose
432
+ motion_update_msg.header.frame_id = frame_id
433
+ motion_update_msg.header.stamp = self.get_clock().now().to_msg()
434
+ motion_update_msg.target_stiffness = np.diag(self.control_stiffness_diag).flatten()
435
+ motion_update_msg.target_damping = np.diag(self.control_damping_diag).flatten()
436
+ motion_update_msg.feedforward_wrench_at_tip = Wrench(
437
+ force=Vector3(x=0.0, y=0.0, z=0.0), torque=Vector3(x=0.0, y=0.0, z=0.0)
438
+ )
439
+ motion_update_msg.wrench_feedback_gains_at_tip = list(
440
+ wrench_feedback_gains if wrench_feedback_gains is not None else [0.0] * 6
441
+ )
442
+ motion_update_msg.trajectory_generation_mode.mode = (
443
+ TrajectoryGenerationMode.MODE_POSITION
444
+ )
445
+ return motion_update_msg
446
+
447
+ def set_cartesian_twist_target(
448
+ self,
449
+ twist: Twist,
450
+ frame_id: str = "base_link",
451
+ wrench_feedback_gains: Sequence[float] | None = None,
452
+ ):
453
+ motion_update_msg = MotionUpdate()
454
+ motion_update_msg.velocity = twist
455
+ motion_update_msg.header.frame_id = frame_id
456
+ motion_update_msg.header.stamp = self.get_clock().now().to_msg()
457
+ motion_update_msg.target_stiffness = np.diag(self.control_stiffness_diag).flatten()
458
+ motion_update_msg.target_damping = np.diag(self.control_damping_diag).flatten()
459
+ motion_update_msg.feedforward_wrench_at_tip = Wrench(
460
+ force=Vector3(x=0.0, y=0.0, z=0.0), torque=Vector3(x=0.0, y=0.0, z=0.0)
461
+ )
462
+ motion_update_msg.wrench_feedback_gains_at_tip = list(
463
+ wrench_feedback_gains if wrench_feedback_gains is not None else [0.0] * 6
464
+ )
465
+ motion_update_msg.trajectory_generation_mode.mode = (
466
+ TrajectoryGenerationMode.MODE_VELOCITY
467
+ )
468
+ return motion_update_msg
policy/aic_example_policies/ros/RunACTStaged.py ADDED
@@ -0,0 +1,1431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2026 Intrinsic Innovation LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import time
21
+ from collections import deque
22
+ from typing import Sequence
23
+
24
+ import numpy as np
25
+ import torch
26
+ from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3
27
+ from rclpy.time import Time
28
+ from tf2_ros import TransformException
29
+
30
+ from aic_model.policy import (
31
+ GetObservationCallback,
32
+ MoveRobotCallback,
33
+ SendFeedbackCallback,
34
+ )
35
+ from aic_task_interfaces.msg import Task
36
+
37
+ from .RunACTCompetitor import (
38
+ RunACTCompetitor,
39
+ _parse_bool,
40
+ _parse_float,
41
+ _parse_float_list,
42
+ )
43
+ from .sfp_tuning_profiles import (
44
+ get_sfp_primitive_tuning_profile,
45
+ is_sfp_gentle_reference_tuning,
46
+ )
47
+
48
+
49
+ def _parse_float_alias(primary: str, alias: str, default: float) -> float:
50
+ value = os.environ.get(primary)
51
+ if value is None:
52
+ value = os.environ.get(alias)
53
+ return float(value) if value is not None else default
54
+
55
+
56
+ def _parse_bool_alias(primary: str, alias: str, default: bool) -> bool:
57
+ value = os.environ.get(primary)
58
+ if value is None:
59
+ value = os.environ.get(alias)
60
+ if value is None:
61
+ return default
62
+ return value.strip().lower() in {"1", "true", "yes", "on"}
63
+
64
+
65
+ def _parse_float_list_alias(
66
+ primary: str, alias: str, default: Sequence[float]
67
+ ) -> list[float]:
68
+ value = os.environ.get(primary)
69
+ if value is None:
70
+ value = os.environ.get(alias)
71
+ if value is None:
72
+ return list(default)
73
+ parsed = [float(part.strip()) for part in value.split(",") if part.strip()]
74
+ if len(parsed) != len(default):
75
+ raise ValueError(
76
+ f"{primary}/{alias} expected {len(default)} comma-separated floats, got {len(parsed)}"
77
+ )
78
+ return parsed
79
+
80
+
81
+ def _quat_xyzw_to_array(quaternion: Quaternion) -> np.ndarray:
82
+ quat = np.array(
83
+ [
84
+ float(quaternion.x),
85
+ float(quaternion.y),
86
+ float(quaternion.z),
87
+ float(quaternion.w),
88
+ ],
89
+ dtype=np.float64,
90
+ )
91
+ norm = float(np.linalg.norm(quat))
92
+ if norm <= 1.0e-9:
93
+ return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
94
+ return quat / norm
95
+
96
+
97
+ def _quat_xyzw_multiply(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
98
+ x1, y1, z1, w1 = q1
99
+ x2, y2, z2, w2 = q2
100
+ return np.array(
101
+ [
102
+ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
103
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
104
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
105
+ w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
106
+ ],
107
+ dtype=np.float64,
108
+ )
109
+
110
+
111
+ def _quat_xyzw_inverse(quat: np.ndarray) -> np.ndarray:
112
+ quat = quat / max(float(np.linalg.norm(quat)), 1.0e-9)
113
+ return np.array([-quat[0], -quat[1], -quat[2], quat[3]], dtype=np.float64)
114
+
115
+
116
+ def _quat_xyzw_to_msg(quat: np.ndarray) -> Quaternion:
117
+ quat = quat / max(float(np.linalg.norm(quat)), 1.0e-9)
118
+ return Quaternion(
119
+ x=float(quat[0]),
120
+ y=float(quat[1]),
121
+ z=float(quat[2]),
122
+ w=float(quat[3]),
123
+ )
124
+
125
+
126
+ class RunACTStaged(RunACTCompetitor):
127
+ """Pose-preserving ACT runtime with staged approach / align / guarded insert / retry."""
128
+
129
+ def __init__(self, parent_node):
130
+ super().__init__(parent_node)
131
+ self.sfp_primitive_tuning_profile = get_sfp_primitive_tuning_profile()
132
+ self._sfp_gentle_reference_tuning = is_sfp_gentle_reference_tuning(
133
+ self.sfp_primitive_tuning_profile
134
+ )
135
+ self.stage_policy_routes = {
136
+ "APPROACH": self._resolve_stage_policy_route(
137
+ phase="APPROACH",
138
+ env_var="AIC_ACT_STAGE_ROUTE_APPROACH",
139
+ default_route="approach",
140
+ ),
141
+ "ALIGN": self._resolve_stage_policy_route(
142
+ phase="ALIGN",
143
+ env_var="AIC_ACT_STAGE_ROUTE_ALIGN",
144
+ default_route="align",
145
+ ),
146
+ "GUARDED_INSERT": self._resolve_stage_policy_route(
147
+ phase="GUARDED_INSERT",
148
+ env_var="AIC_ACT_STAGE_ROUTE_GUARDED_INSERT",
149
+ default_route="guarded_insert",
150
+ ),
151
+ "RETRY_OR_FINISH": self._resolve_stage_policy_route(
152
+ phase="RETRY_OR_FINISH",
153
+ env_var="AIC_ACT_STAGE_ROUTE_RETRY_OR_FINISH",
154
+ default_route="retry_or_finish",
155
+ ),
156
+ }
157
+ self.enable_staged_wrapper = _parse_bool_alias(
158
+ "AIC_ACT_STAGED_ENABLE_STAGED_WRAPPER",
159
+ "enable_staged_wrapper",
160
+ True,
161
+ )
162
+ self.approach_offset = np.asarray(
163
+ _parse_float_list_alias(
164
+ "AIC_ACT_STAGED_APPROACH_OFFSET",
165
+ "approach_offset",
166
+ [0.0, 0.0, 0.0],
167
+ ),
168
+ dtype=np.float64,
169
+ )
170
+ self.insertion_speed_scale = _parse_float_alias(
171
+ "AIC_ACT_STAGED_INSERTION_SPEED_SCALE",
172
+ "insertion_speed_scale",
173
+ 0.35,
174
+ )
175
+ self.guarded_insert_force_start_n = _parse_float_alias(
176
+ "AIC_ACT_STAGED_GUARDED_INSERT_FORCE_START_N",
177
+ "guarded_insert_force_start",
178
+ self.force_rampdown_start_n,
179
+ )
180
+ self.guarded_insert_force_stop_n = _parse_float_alias(
181
+ "AIC_ACT_STAGED_GUARDED_INSERT_FORCE_STOP_N",
182
+ "guarded_insert_force_stop",
183
+ self.force_hard_stop_n,
184
+ )
185
+ self.max_retries = int(
186
+ _parse_float_alias(
187
+ "AIC_ACT_STAGED_RETRY_COUNT",
188
+ "retry_count",
189
+ 1.0,
190
+ )
191
+ )
192
+ self.backout_distance_m = _parse_float_alias(
193
+ "AIC_ACT_STAGED_BACKOUT_DISTANCE_M",
194
+ "backout_distance",
195
+ 0.010,
196
+ )
197
+ self.settle_time_s = _parse_float_alias(
198
+ "AIC_ACT_STAGED_SETTLE_TIME_S",
199
+ "settle_time",
200
+ 0.75,
201
+ )
202
+ self.require_insertion_event = _parse_bool_alias(
203
+ "AIC_ACT_STAGED_REQUIRE_INSERTION_EVENT",
204
+ "require_insertion_event",
205
+ self.require_insertion_event,
206
+ )
207
+ self.approach_min_sec = _parse_float(
208
+ "AIC_ACT_STAGED_APPROACH_MIN_SEC", 0.75
209
+ )
210
+ self.max_guarded_insert_sec = _parse_float(
211
+ "AIC_ACT_STAGED_MAX_GUARDED_INSERT_SEC",
212
+ 6.00 if self._sfp_gentle_reference_tuning else 1.50,
213
+ )
214
+ self.align_position_tolerance_m = _parse_float(
215
+ "AIC_ACT_STAGED_ALIGN_POSITION_TOL_M", 0.025
216
+ )
217
+ self.align_xy_error_tolerance_m = _parse_float(
218
+ "AIC_ACT_STAGED_ALIGN_XY_ERROR_TOL_M", 0.015
219
+ )
220
+ self.align_angular_tolerance_rad = _parse_float(
221
+ "AIC_ACT_STAGED_ALIGN_ANGULAR_TOL_RAD", 0.12
222
+ )
223
+ self.guard_progress_epsilon_m = _parse_float(
224
+ "AIC_ACT_STAGED_PROGRESS_EPS_M",
225
+ 0.0004 if self._sfp_gentle_reference_tuning else 0.0015,
226
+ )
227
+ self.guard_position_smoothing_scale = _parse_float(
228
+ "AIC_ACT_STAGED_ALIGN_SMOOTHING_SCALE", 0.25
229
+ )
230
+ self.geometry_debug_enabled = _parse_bool(
231
+ "AIC_ACT_STAGED_GEOMETRY_DEBUG", False
232
+ )
233
+ self.privileged_terminal_target_enabled = _parse_bool(
234
+ "AIC_ACT_STAGED_PRIVILEGED_TERMINAL_TARGET", False
235
+ )
236
+ self.privileged_hover_offset_m = _parse_float(
237
+ "AIC_ACT_STAGED_PRIVILEGED_HOVER_OFFSET_M", 0.160
238
+ )
239
+ self.privileged_align_offset_m = _parse_float(
240
+ "AIC_ACT_STAGED_PRIVILEGED_ALIGN_OFFSET_M", 0.130
241
+ )
242
+ self.privileged_insert_target_offset_m = _parse_float(
243
+ "AIC_ACT_STAGED_PRIVILEGED_INSERT_TARGET_OFFSET_M", 0.105
244
+ )
245
+ self.privileged_xy_integrator_gain = _parse_float(
246
+ "AIC_ACT_STAGED_PRIVILEGED_XY_INTEGRATOR_GAIN", 0.15
247
+ )
248
+ self.privileged_xy_direct_gain = _parse_float(
249
+ "AIC_ACT_STAGED_PRIVILEGED_XY_DIRECT_GAIN", 0.0
250
+ )
251
+ self.privileged_xy_integrator_windup_m = _parse_float(
252
+ "AIC_ACT_STAGED_PRIVILEGED_XY_INTEGRATOR_WINDUP_M", 0.050
253
+ )
254
+ self.privileged_ready_xy_tol_m = _parse_float(
255
+ "AIC_ACT_STAGED_PRIVILEGED_READY_XY_TOL_M", 0.006
256
+ )
257
+ self.privileged_guard_lateral_gain = _parse_float(
258
+ "AIC_ACT_STAGED_PRIVILEGED_GUARD_LATERAL_GAIN", 0.60
259
+ )
260
+ self.privileged_debug_every_n = int(
261
+ _parse_float("AIC_ACT_STAGED_PRIVILEGED_DEBUG_EVERY_N", 10.0)
262
+ )
263
+ self._last_guidance_context: dict[str, object] | None = None
264
+ self._privileged_debug_counter = 0
265
+ self._privileged_tip_xy_error_integrator = np.zeros(2, dtype=np.float64)
266
+ self._recent_act_pose_positions: deque[np.ndarray] = deque(maxlen=6)
267
+ self._phase = "APPROACH"
268
+ self._phase_start_time = 0.0
269
+ self._align_stable_since: float | None = None
270
+ self._guard_direction: np.ndarray | None = None
271
+ self._guard_start_pos: np.ndarray | None = None
272
+ self._best_guard_progress_m = 0.0
273
+ self._retry_target_pose: Pose | None = None
274
+ self._retry_reason = ""
275
+ self._retries_used = 0
276
+ self._max_force_seen_n = 0.0
277
+ self.get_logger().info(
278
+ "RunACTStaged active with "
279
+ f"enable_staged_wrapper={self.enable_staged_wrapper} "
280
+ f"approach_offset={self.approach_offset.tolist()} "
281
+ f"insertion_speed_scale={self.insertion_speed_scale:.3f} "
282
+ f"guarded_force=({self.guarded_insert_force_start_n:.1f}, {self.guarded_insert_force_stop_n:.1f}) "
283
+ f"retry_count={self.max_retries} "
284
+ f"backout_distance_m={self.backout_distance_m:.3f} "
285
+ f"settle_time_s={self.settle_time_s:.3f} "
286
+ f"require_insertion_event={self.require_insertion_event} "
287
+ f"sfp_tuning_profile={self.sfp_primitive_tuning_profile}"
288
+ )
289
+ self.get_logger().info(
290
+ "RunACTStaged stage policy routes: "
291
+ + ", ".join(
292
+ f"{phase}={route or '<task-default>'}"
293
+ for phase, route in self.stage_policy_routes.items()
294
+ )
295
+ )
296
+ if self.privileged_terminal_target_enabled:
297
+ self.get_logger().warning(
298
+ "RunACTStaged privileged terminal target is ENABLED. "
299
+ "This is for local geometry diagnosis only and is not submission-safe."
300
+ )
301
+ else:
302
+ self.get_logger().info(
303
+ "RunACTStaged uses ACT-led pose targets with staged heuristics. "
304
+ "No explicit target geometry is available in the current Observation/Task path."
305
+ )
306
+
307
+ @staticmethod
308
+ def _norm(values: Sequence[float]) -> float:
309
+ return float(np.linalg.norm(np.asarray(values, dtype=np.float64)))
310
+
311
+ @staticmethod
312
+ def _pose_position_array(pose: Pose) -> np.ndarray:
313
+ return np.array(
314
+ [pose.position.x, pose.position.y, pose.position.z], dtype=np.float64
315
+ )
316
+
317
+ @staticmethod
318
+ def _copy_pose(pose: Pose) -> Pose:
319
+ return Pose(
320
+ position=Point(
321
+ x=float(pose.position.x),
322
+ y=float(pose.position.y),
323
+ z=float(pose.position.z),
324
+ ),
325
+ orientation=Quaternion(
326
+ x=float(pose.orientation.x),
327
+ y=float(pose.orientation.y),
328
+ z=float(pose.orientation.z),
329
+ w=float(pose.orientation.w),
330
+ ),
331
+ )
332
+
333
+ @staticmethod
334
+ def _normalized(vector: np.ndarray, fallback: np.ndarray) -> np.ndarray:
335
+ norm = float(np.linalg.norm(vector))
336
+ if norm <= 1e-9:
337
+ return fallback.copy()
338
+ return vector / norm
339
+
340
+ def _build_guidance_context(self, observation_msg, task: Task):
341
+ if not (self.geometry_debug_enabled or self.privileged_terminal_target_enabled):
342
+ self._last_guidance_context = None
343
+ return None
344
+ context = self._build_privileged_terminal_context(observation_msg, task)
345
+ self._last_guidance_context = context
346
+ return context
347
+
348
+ def _apply_guidance_pose(
349
+ self,
350
+ pose: Pose,
351
+ observation_msg,
352
+ task: Task,
353
+ guidance_context,
354
+ ) -> Pose:
355
+ if (
356
+ not self.privileged_terminal_target_enabled
357
+ or guidance_context is None
358
+ or not guidance_context.get("available")
359
+ ):
360
+ return pose
361
+ phase = str(getattr(self, "_phase", "APPROACH"))
362
+ if phase == "APPROACH":
363
+ target_pose = guidance_context.get("hover_pose")
364
+ elif phase == "ALIGN":
365
+ target_pose = guidance_context.get("align_pose")
366
+ else:
367
+ target_pose = guidance_context.get("insert_pose")
368
+ return self._copy_pose(target_pose) if isinstance(target_pose, Pose) else pose
369
+
370
+ def _guidance_allows_align(self, guidance_context) -> bool:
371
+ if not self.privileged_terminal_target_enabled:
372
+ return True
373
+ return bool(
374
+ guidance_context is not None
375
+ and guidance_context.get("available")
376
+ and guidance_context.get("ready_for_align")
377
+ )
378
+
379
+ def _guidance_allows_guarded_insert(self, guidance_context) -> bool:
380
+ if not self.privileged_terminal_target_enabled:
381
+ return True
382
+ allowed = bool(
383
+ guidance_context is not None
384
+ and guidance_context.get("available")
385
+ and guidance_context.get("ready_for_insert")
386
+ )
387
+ if allowed and guidance_context is not None:
388
+ insert_axis = guidance_context.get("insert_direction_world")
389
+ if isinstance(insert_axis, np.ndarray):
390
+ self._guard_direction = insert_axis.copy()
391
+ return allowed
392
+
393
+ def _guidance_retry_phase(self, guidance_context) -> str:
394
+ if self.privileged_terminal_target_enabled:
395
+ return "ALIGN"
396
+ return "ALIGN"
397
+
398
+ def _guidance_summary(self, guidance_context) -> str:
399
+ if guidance_context is None or not guidance_context.get("available"):
400
+ return ""
401
+ xy = guidance_context.get("plug_port_xy_error_m")
402
+ dist = guidance_context.get("plug_port_distance_m")
403
+ depth = guidance_context.get("insertion_depth_m")
404
+ frac = guidance_context.get("insertion_fraction")
405
+ ready = guidance_context.get("ready_for_insert")
406
+ return (
407
+ f"gt_xy={xy:.4f}m gt_dist={dist:.4f}m "
408
+ f"gt_depth={depth:.4f}m gt_frac={frac:.3f} gt_ready={ready}"
409
+ )
410
+
411
+ def _lookup_tf_transform(self, target_frame: str, source_frame: str):
412
+ return self._parent_node._tf_buffer.lookup_transform(
413
+ target_frame,
414
+ source_frame,
415
+ Time(),
416
+ ).transform
417
+
418
+ @staticmethod
419
+ def _transform_translation_array(transform) -> np.ndarray:
420
+ return np.array(
421
+ [
422
+ float(transform.translation.x),
423
+ float(transform.translation.y),
424
+ float(transform.translation.z),
425
+ ],
426
+ dtype=np.float64,
427
+ )
428
+
429
+ def _privileged_gripper_pose_for_offset(
430
+ self,
431
+ *,
432
+ port_transform,
433
+ plug_transform,
434
+ gripper_transform,
435
+ z_offset_m: float,
436
+ target_xy_offset_m: np.ndarray,
437
+ ) -> Pose:
438
+ q_port = _quat_xyzw_to_array(port_transform.rotation)
439
+ q_plug = _quat_xyzw_to_array(plug_transform.rotation)
440
+ q_gripper = _quat_xyzw_to_array(gripper_transform.rotation)
441
+ q_diff = _quat_xyzw_multiply(q_port, _quat_xyzw_inverse(q_plug))
442
+ q_gripper_target = _quat_xyzw_multiply(q_diff, q_gripper)
443
+
444
+ port_xyz = self._transform_translation_array(port_transform)
445
+ plug_xyz = self._transform_translation_array(plug_transform)
446
+ gripper_xyz = self._transform_translation_array(gripper_transform)
447
+ plug_tip_gripper_offset = gripper_xyz - plug_xyz
448
+ target_xy = port_xyz[:2] + target_xy_offset_m
449
+ target_z = port_xyz[2] + float(z_offset_m) - plug_tip_gripper_offset[2]
450
+ return Pose(
451
+ position=Point(
452
+ x=float(target_xy[0]),
453
+ y=float(target_xy[1]),
454
+ z=float(target_z),
455
+ ),
456
+ orientation=_quat_xyzw_to_msg(q_gripper_target),
457
+ )
458
+
459
+ def _build_privileged_terminal_context(self, observation_msg, task: Task):
460
+ port_frame = f"task_board/{task.target_module_name}/{task.port_name}_link"
461
+ port_entrance_frame = f"{port_frame}_entrance"
462
+ plug_frame = f"{task.cable_name}/{task.plug_name}_link"
463
+ gripper_frame = os.environ.get(
464
+ "AIC_ACT_STAGED_PRIVILEGED_GRIPPER_FRAME", "gripper/tcp"
465
+ )
466
+ try:
467
+ port_tf = self._lookup_tf_transform("base_link", port_frame)
468
+ port_entrance_tf = self._lookup_tf_transform(
469
+ "base_link", port_entrance_frame
470
+ )
471
+ plug_tf = self._lookup_tf_transform("base_link", plug_frame)
472
+ gripper_tf = self._lookup_tf_transform("base_link", gripper_frame)
473
+ except TransformException as ex:
474
+ if self.geometry_debug_enabled or self.privileged_terminal_target_enabled:
475
+ self.get_logger().warning(
476
+ f"Privileged terminal geometry unavailable: {ex}"
477
+ )
478
+ return {"available": False, "error": str(ex)}
479
+
480
+ port_xyz = self._transform_translation_array(port_tf)
481
+ entrance_xyz = self._transform_translation_array(port_entrance_tf)
482
+ plug_xyz = self._transform_translation_array(plug_tf)
483
+ gripper_xyz = self._transform_translation_array(gripper_tf)
484
+ plug_port_delta = plug_xyz - port_xyz
485
+ tip_xy_error = port_xyz[:2] - plug_xyz[:2]
486
+ self._privileged_tip_xy_error_integrator = np.clip(
487
+ self._privileged_tip_xy_error_integrator + tip_xy_error,
488
+ -self.privileged_xy_integrator_windup_m,
489
+ self.privileged_xy_integrator_windup_m,
490
+ )
491
+ target_xy_offset_m = (
492
+ self.privileged_xy_direct_gain * tip_xy_error
493
+ + self.privileged_xy_integrator_gain
494
+ * self._privileged_tip_xy_error_integrator
495
+ )
496
+ xy_error = float(np.linalg.norm(plug_port_delta[:2]))
497
+ distance = float(np.linalg.norm(plug_port_delta))
498
+ port_depth = max(float(entrance_xyz[2] - port_xyz[2]), 1.0e-6)
499
+ insertion_depth = float(entrance_xyz[2] - plug_xyz[2])
500
+ insertion_fraction = float(insertion_depth / port_depth)
501
+ hover_pose = self._privileged_gripper_pose_for_offset(
502
+ port_transform=port_tf,
503
+ plug_transform=plug_tf,
504
+ gripper_transform=gripper_tf,
505
+ z_offset_m=self.privileged_hover_offset_m,
506
+ target_xy_offset_m=target_xy_offset_m,
507
+ )
508
+ align_pose = self._privileged_gripper_pose_for_offset(
509
+ port_transform=port_tf,
510
+ plug_transform=plug_tf,
511
+ gripper_transform=gripper_tf,
512
+ z_offset_m=self.privileged_align_offset_m,
513
+ target_xy_offset_m=target_xy_offset_m,
514
+ )
515
+ insert_pose = self._privileged_gripper_pose_for_offset(
516
+ port_transform=port_tf,
517
+ plug_transform=plug_tf,
518
+ gripper_transform=gripper_tf,
519
+ z_offset_m=self.privileged_insert_target_offset_m,
520
+ target_xy_offset_m=target_xy_offset_m,
521
+ )
522
+ insert_axis = np.array([0.0, 0.0, -1.0], dtype=np.float64)
523
+ ready_for_align = xy_error <= max(0.025, self.privileged_ready_xy_tol_m * 4.0)
524
+ ready_for_insert = xy_error <= self.privileged_ready_xy_tol_m
525
+ current_pose = self._current_tcp_pose(observation_msg)
526
+ current_xyz = self._pose_position_array(current_pose)
527
+ guard_target_xyz = self._pose_position_array(insert_pose)
528
+ raw_lateral = guard_target_xyz - current_xyz
529
+ raw_lateral = raw_lateral - float(np.dot(raw_lateral, insert_axis)) * insert_axis
530
+ context = {
531
+ "available": True,
532
+ "vision_mode": "privileged_terminal_target",
533
+ "advisory_only": not self.privileged_terminal_target_enabled,
534
+ "guidance_applied": bool(self.privileged_terminal_target_enabled),
535
+ "guidance_would_apply": True,
536
+ "ready_for_align": ready_for_align,
537
+ "ready_for_insert": ready_for_insert,
538
+ "port_frame": port_frame,
539
+ "port_entrance_frame": port_entrance_frame,
540
+ "plug_frame": plug_frame,
541
+ "gripper_frame": gripper_frame,
542
+ "port_position": port_xyz.astype(float).tolist(),
543
+ "port_entrance_position": entrance_xyz.astype(float).tolist(),
544
+ "plug_position": plug_xyz.astype(float).tolist(),
545
+ "gripper_position": gripper_xyz.astype(float).tolist(),
546
+ "plug_port_delta_m": plug_port_delta.astype(float).tolist(),
547
+ "privileged_tip_xy_error_integrator_m": self._privileged_tip_xy_error_integrator.astype(float).tolist(),
548
+ "privileged_target_xy_offset_m": target_xy_offset_m.astype(float).tolist(),
549
+ "plug_port_xy_error_m": xy_error,
550
+ "plug_port_distance_m": distance,
551
+ "insertion_depth_m": insertion_depth,
552
+ "insertion_fraction": insertion_fraction,
553
+ "hover_pose": hover_pose,
554
+ "align_pose": align_pose,
555
+ "insert_pose": insert_pose,
556
+ "insert_direction_world": insert_axis,
557
+ "guard_lateral_correction_world_m": (
558
+ self.privileged_guard_lateral_gain * raw_lateral
559
+ ).astype(float).tolist(),
560
+ "proposed_local_offset_m": plug_port_delta.astype(float).tolist(),
561
+ "proposed_world_offset_m": plug_port_delta.astype(float).tolist(),
562
+ }
563
+ self._log_privileged_terminal_context(context)
564
+ return context
565
+
566
+ def _log_privileged_terminal_context(self, context: dict[str, object]) -> None:
567
+ if not (self.geometry_debug_enabled or self.privileged_terminal_target_enabled):
568
+ return
569
+ every = max(self.privileged_debug_every_n, 1)
570
+ self._privileged_debug_counter += 1
571
+ phase = str(getattr(self, "_phase", "unknown"))
572
+ important_phase = phase in {"ALIGN", "GUARDED_INSERT", "RETRY_OR_FINISH"}
573
+ if self._privileged_debug_counter % every != 0 and not important_phase:
574
+ return
575
+ self.get_logger().info(
576
+ "privileged_terminal_geometry "
577
+ f"phase={phase} "
578
+ f"xy_error_m={context['plug_port_xy_error_m']:.5f} "
579
+ f"distance_m={context['plug_port_distance_m']:.5f} "
580
+ f"depth_m={context['insertion_depth_m']:.5f} "
581
+ f"fraction={context['insertion_fraction']:.3f} "
582
+ f"ready_align={context['ready_for_align']} "
583
+ f"ready_insert={context['ready_for_insert']} "
584
+ f"target_enabled={self.privileged_terminal_target_enabled}"
585
+ )
586
+
587
+ def _reset_privileged_terminal_guidance(self) -> None:
588
+ self._last_guidance_context = None
589
+ self._privileged_debug_counter = 0
590
+ self._privileged_tip_xy_error_integrator = np.zeros(2, dtype=np.float64)
591
+
592
+ def _guidance_result_fields(self, guidance_context) -> dict[str, object]:
593
+ if guidance_context is None or not guidance_context.get("available"):
594
+ return {
595
+ "gt_geometry_available": False,
596
+ "gt_plug_port_xy_error_m": None,
597
+ "gt_plug_port_distance_m": None,
598
+ "gt_insertion_depth_m": None,
599
+ "gt_insertion_fraction": None,
600
+ "gt_ready_for_align": None,
601
+ "gt_ready_for_insert": None,
602
+ "gt_terminal_target_enabled": bool(
603
+ self.privileged_terminal_target_enabled
604
+ ),
605
+ }
606
+ return {
607
+ "gt_geometry_available": True,
608
+ "gt_plug_port_xy_error_m": guidance_context.get("plug_port_xy_error_m"),
609
+ "gt_plug_port_distance_m": guidance_context.get("plug_port_distance_m"),
610
+ "gt_insertion_depth_m": guidance_context.get("insertion_depth_m"),
611
+ "gt_insertion_fraction": guidance_context.get("insertion_fraction"),
612
+ "gt_ready_for_align": guidance_context.get("ready_for_align"),
613
+ "gt_ready_for_insert": guidance_context.get("ready_for_insert"),
614
+ "gt_terminal_target_enabled": bool(self.privileged_terminal_target_enabled),
615
+ }
616
+
617
+ def _privileged_guard_pose_adjustment(
618
+ self,
619
+ proposed_pose: Pose,
620
+ observation_msg,
621
+ task: Task | None,
622
+ ) -> Pose:
623
+ if (
624
+ not self.privileged_terminal_target_enabled
625
+ or task is None
626
+ or not self.enable_staged_wrapper
627
+ ):
628
+ return proposed_pose
629
+ guidance_context = self._build_guidance_context(observation_msg, task)
630
+ if guidance_context is None or not guidance_context.get("available"):
631
+ return proposed_pose
632
+ insert_axis = guidance_context.get("insert_direction_world")
633
+ lateral = guidance_context.get("guard_lateral_correction_world_m")
634
+ insert_pose = guidance_context.get("insert_pose")
635
+ if not isinstance(insert_axis, np.ndarray) or not isinstance(lateral, list):
636
+ return proposed_pose
637
+ adjusted = self._copy_pose(proposed_pose)
638
+ current_pos = self._pose_position_array(self._current_tcp_pose(observation_msg))
639
+ proposed_pos = self._pose_position_array(proposed_pose)
640
+ axial_delta = float(np.dot(proposed_pos - current_pos, insert_axis))
641
+ lateral_vec = np.asarray(lateral, dtype=np.float64)
642
+ adjusted_pos = current_pos + axial_delta * insert_axis + lateral_vec
643
+ adjusted.position = Point(
644
+ x=float(adjusted_pos[0]),
645
+ y=float(adjusted_pos[1]),
646
+ z=float(adjusted_pos[2]),
647
+ )
648
+ if isinstance(insert_pose, Pose):
649
+ adjusted.orientation = insert_pose.orientation
650
+ return adjusted
651
+ return adjusted
652
+
653
+ def _resolve_stage_policy_route(
654
+ self,
655
+ *,
656
+ phase: str,
657
+ env_var: str,
658
+ default_route: str,
659
+ ) -> str | None:
660
+ configured = self._normalize_route_text(os.environ.get(env_var))
661
+ if configured:
662
+ return configured
663
+ if default_route in self._policy_bundles:
664
+ return default_route
665
+ return None
666
+
667
+ def _activate_phase_policy_bundle(
668
+ self, phase: str, reason: str = ""
669
+ ) -> str:
670
+ route_key = self.stage_policy_routes.get(phase)
671
+ if not route_key:
672
+ return self._active_policy_route
673
+ if route_key not in self._policy_bundles:
674
+ self.get_logger().warning(
675
+ f"Stage route {route_key!r} for phase {phase} is not loaded; "
676
+ f"continuing with route={self._active_policy_route!r}"
677
+ )
678
+ return self._active_policy_route
679
+ if route_key != self._active_policy_route:
680
+ self._activate_policy_bundle(
681
+ route_key, reason=f"phase={phase} {reason}".strip()
682
+ )
683
+ self.policy.reset()
684
+ return self._active_policy_route
685
+
686
+ def _set_phase(self, phase: str, now: float, reason: str = "") -> None:
687
+ if self._phase == phase:
688
+ return
689
+ self._phase = phase
690
+ self._phase_start_time = now
691
+ self._recent_act_pose_positions.clear()
692
+ if phase != "ALIGN":
693
+ self._align_stable_since = None
694
+ if phase != "GUARDED_INSERT":
695
+ self._guard_start_pos = None
696
+ self._best_guard_progress_m = 0.0
697
+ if phase != "RETRY_OR_FINISH":
698
+ self._retry_target_pose = None
699
+ self._retry_reason = ""
700
+ self._activate_phase_policy_bundle(phase, reason=reason)
701
+ suffix = f" ({reason})" if reason else ""
702
+ self.get_logger().info(f"RunACTStaged phase -> {phase}{suffix}")
703
+
704
+ def _record_act_pose_target(self, pose: Pose) -> None:
705
+ self._recent_act_pose_positions.append(self._pose_position_array(pose))
706
+
707
+ def _act_target_is_stable(self) -> bool:
708
+ if len(self._recent_act_pose_positions) < self._recent_act_pose_positions.maxlen:
709
+ return False
710
+ positions = np.stack(tuple(self._recent_act_pose_positions), axis=0)
711
+ span = np.max(positions, axis=0) - np.min(positions, axis=0)
712
+ return float(np.linalg.norm(span)) <= self.align_position_tolerance_m
713
+
714
+ def _current_tcp_pose(self, observation_msg) -> Pose:
715
+ return observation_msg.controller_state.tcp_pose
716
+
717
+ def _tcp_error_metrics(self, observation_msg) -> tuple[float, float, float]:
718
+ tcp_error = observation_msg.controller_state.tcp_error
719
+ position_error = self._norm(tcp_error[:3])
720
+ xy_error = self._norm(tcp_error[:2])
721
+ angular_error = self._norm(tcp_error[3:6])
722
+ return position_error, xy_error, angular_error
723
+
724
+ def _apply_position_offset(self, pose: Pose, offset_xyz: np.ndarray) -> Pose:
725
+ offset_pose = self._copy_pose(pose)
726
+ offset_pose.position.x += float(offset_xyz[0])
727
+ offset_pose.position.y += float(offset_xyz[1])
728
+ offset_pose.position.z += float(offset_xyz[2])
729
+ return offset_pose
730
+
731
+ def _interpolate_pose(
732
+ self,
733
+ current_pose: Pose,
734
+ target_pose: Pose,
735
+ position_scale: float,
736
+ ) -> Pose:
737
+ current = self._pose_position_array(current_pose)
738
+ target = self._pose_position_array(target_pose)
739
+ alpha = float(np.clip(position_scale, 0.0, 1.0))
740
+ shaped = current + alpha * (target - current)
741
+ pose = self._copy_pose(target_pose)
742
+ pose.position = Point(
743
+ x=float(shaped[0]),
744
+ y=float(shaped[1]),
745
+ z=float(shaped[2]),
746
+ )
747
+ return pose
748
+
749
+ def _estimate_insert_direction(
750
+ self,
751
+ observation_msg,
752
+ act_pose: Pose,
753
+ ) -> np.ndarray:
754
+ if self.privileged_terminal_target_enabled:
755
+ guidance_context = self._last_guidance_context
756
+ if guidance_context is not None:
757
+ insert_axis = guidance_context.get("insert_direction_world")
758
+ if isinstance(insert_axis, np.ndarray):
759
+ return insert_axis.copy()
760
+ current_pos = self._pose_position_array(self._current_tcp_pose(observation_msg))
761
+ target_pos = self._pose_position_array(act_pose)
762
+ target_delta = target_pos - current_pos
763
+ if float(np.linalg.norm(target_delta)) > 2.0e-3:
764
+ return self._normalized(target_delta, np.array([0.0, 0.0, -1.0]))
765
+ if len(self._recent_act_pose_positions) >= 2:
766
+ recent_delta = self._recent_act_pose_positions[-1] - self._recent_act_pose_positions[0]
767
+ if float(np.linalg.norm(recent_delta)) > 1.0e-3:
768
+ return self._normalized(recent_delta, np.array([0.0, 0.0, -1.0]))
769
+ return np.array([0.0, 0.0, -1.0], dtype=np.float64)
770
+
771
+ def _enter_retry(
772
+ self,
773
+ observation_msg,
774
+ insert_direction: np.ndarray,
775
+ now: float,
776
+ reason: str,
777
+ ) -> None:
778
+ current_pose = self._current_tcp_pose(observation_msg)
779
+ current_pos = self._pose_position_array(current_pose)
780
+ backout_pos = current_pos - insert_direction * self.backout_distance_m
781
+ self._retry_target_pose = Pose(
782
+ position=Point(
783
+ x=float(backout_pos[0]),
784
+ y=float(backout_pos[1]),
785
+ z=float(backout_pos[2]),
786
+ ),
787
+ orientation=current_pose.orientation,
788
+ )
789
+ self._retry_reason = reason
790
+ self._retries_used += 1
791
+ self._set_phase("RETRY_OR_FINISH", now, reason=reason)
792
+
793
+ def _maybe_finish_without_event(self, reason: str) -> bool:
794
+ self.get_logger().info(
795
+ "RunACTStaged finishing without insertion event. "
796
+ f"reason={reason} require_insertion_event={self.require_insertion_event} "
797
+ f"max_force_seen_n={self._max_force_seen_n:.4f}"
798
+ )
799
+ return True if not self.require_insertion_event else self._insertion_event_seen
800
+
801
+ def step(self, action: np.ndarray) -> dict[str, object]:
802
+ if self._active_observation_msg is None:
803
+ raise RuntimeError("No active observation is available for wrapper step().")
804
+ if self._active_task is None:
805
+ raise RuntimeError("No active task is available for wrapper step().")
806
+ if self._active_move_robot is None:
807
+ raise RuntimeError("No active move_robot callback is available for step().")
808
+ if action.shape[0] < 6:
809
+ raise RuntimeError(
810
+ f"ACT action has unexpected shape {action.shape}; need at least 6 dims"
811
+ )
812
+
813
+ observation_msg = self._active_observation_msg
814
+ task = self._active_task
815
+ move_robot = self._active_move_robot
816
+ guidance_context = self._build_guidance_context(observation_msg, task)
817
+ guidance_summary = self._guidance_summary(guidance_context)
818
+ timestamp = self._clock_now_seconds()
819
+ action_id = self._episode_action_id
820
+ self._episode_action_id += 1
821
+ phase_before = self._phase
822
+ phase_now = self._phase
823
+ loop_now = time.time()
824
+ phase_elapsed = loop_now - self._phase_start_time
825
+
826
+ compensated_force_n = self._compensated_force_magnitude(observation_msg)
827
+ if compensated_force_n is not None:
828
+ self._max_force_seen_n = max(self._max_force_seen_n, compensated_force_n)
829
+
830
+ pose_position = action[6:9] if action.shape[0] >= 9 else np.zeros(3)
831
+ pose_quaternion = None
832
+ joint_targets = action[13:19] if action.shape[0] >= 19 else np.zeros(6)
833
+ shaped_linear_log = None
834
+ shaped_angular_log = None
835
+ shaped_pose_position_log = [float("nan")] * 3
836
+ wrench_feedback_gains = self.base_wrench_feedback_gains.copy()
837
+ action_accepted = False
838
+ action_type = "cartesian_delta"
839
+ termination_reason = None
840
+ wrapper_returned_success = None
841
+ is_recovery = phase_now == "RETRY_OR_FINISH"
842
+
843
+ if not self.enable_staged_wrapper:
844
+ if self.command_mode == "pose" and action.shape[0] >= 13:
845
+ quat = np.array(action[9:13], dtype=np.float64)
846
+ quat_norm = float(np.linalg.norm(quat))
847
+ quat = (
848
+ np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
849
+ if quat_norm < 1e-8
850
+ else quat / quat_norm
851
+ )
852
+ pose_quaternion = quat.astype(float).tolist()
853
+ pose = Pose(
854
+ position=Point(
855
+ x=float(action[6]),
856
+ y=float(action[7]),
857
+ z=float(action[8]),
858
+ ),
859
+ orientation=Quaternion(
860
+ x=float(quat[0]),
861
+ y=float(quat[1]),
862
+ z=float(quat[2]),
863
+ w=float(quat[3]),
864
+ ),
865
+ )
866
+ shaped_pose, wrench_feedback_gains, compensated_force_n = self._shape_pose(
867
+ pose, observation_msg
868
+ )
869
+ shaped_pose_position_log = [
870
+ float(shaped_pose.position.x),
871
+ float(shaped_pose.position.y),
872
+ float(shaped_pose.position.z),
873
+ ]
874
+ action_accepted = bool(
875
+ move_robot(
876
+ motion_update=self.create_pose_motion_update(
877
+ shaped_pose,
878
+ wrench_feedback_gains=wrench_feedback_gains,
879
+ )
880
+ )
881
+ )
882
+ action_type = "pose_target"
883
+ else:
884
+ twist = Twist(
885
+ linear=Vector3(
886
+ x=float(action[0]), y=float(action[1]), z=float(action[2])
887
+ ),
888
+ angular=Vector3(
889
+ x=float(action[3]), y=float(action[4]), z=float(action[5])
890
+ ),
891
+ )
892
+ shaped_twist, wrench_feedback_gains, compensated_force_n = (
893
+ self._shape_twist(twist, observation_msg)
894
+ )
895
+ shaped_linear_log = [
896
+ float(shaped_twist.linear.x),
897
+ float(shaped_twist.linear.y),
898
+ float(shaped_twist.linear.z),
899
+ ]
900
+ shaped_angular_log = [
901
+ float(shaped_twist.angular.x),
902
+ float(shaped_twist.angular.y),
903
+ float(shaped_twist.angular.z),
904
+ ]
905
+ action_accepted = bool(
906
+ move_robot(
907
+ motion_update=self.set_cartesian_twist_target(
908
+ shaped_twist,
909
+ wrench_feedback_gains=wrench_feedback_gains,
910
+ )
911
+ )
912
+ )
913
+ else:
914
+ if self.command_mode != "pose" or action.shape[0] < 13:
915
+ twist = Twist(
916
+ linear=Vector3(
917
+ x=float(action[0]), y=float(action[1]), z=float(action[2])
918
+ ),
919
+ angular=Vector3(
920
+ x=float(action[3]), y=float(action[4]), z=float(action[5])
921
+ ),
922
+ )
923
+ shaped_twist, wrench_feedback_gains, compensated_force_n = (
924
+ self._shape_twist(twist, observation_msg)
925
+ )
926
+ shaped_linear_log = [
927
+ float(shaped_twist.linear.x),
928
+ float(shaped_twist.linear.y),
929
+ float(shaped_twist.linear.z),
930
+ ]
931
+ shaped_angular_log = [
932
+ float(shaped_twist.angular.x),
933
+ float(shaped_twist.angular.y),
934
+ float(shaped_twist.angular.z),
935
+ ]
936
+ action_accepted = bool(
937
+ move_robot(
938
+ motion_update=self.set_cartesian_twist_target(
939
+ shaped_twist,
940
+ wrench_feedback_gains=wrench_feedback_gains,
941
+ )
942
+ )
943
+ )
944
+ else:
945
+ quat = np.array(action[9:13], dtype=np.float64)
946
+ quat_norm = float(np.linalg.norm(quat))
947
+ quat = (
948
+ np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
949
+ if quat_norm < 1e-8
950
+ else quat / quat_norm
951
+ )
952
+ pose_quaternion = quat.astype(float).tolist()
953
+ act_pose = Pose(
954
+ position=Point(
955
+ x=float(action[6]),
956
+ y=float(action[7]),
957
+ z=float(action[8]),
958
+ ),
959
+ orientation=Quaternion(
960
+ x=float(quat[0]),
961
+ y=float(quat[1]),
962
+ z=float(quat[2]),
963
+ w=float(quat[3]),
964
+ ),
965
+ )
966
+ self._record_act_pose_target(act_pose)
967
+ current_pose = self._current_tcp_pose(observation_msg)
968
+ current_pos = self._pose_position_array(current_pose)
969
+ position_error, xy_error, angular_error = self._tcp_error_metrics(
970
+ observation_msg
971
+ )
972
+ action_type = "pose_target"
973
+
974
+ if phase_now == "APPROACH":
975
+ approach_pose = self._apply_position_offset(
976
+ act_pose, self.approach_offset
977
+ )
978
+ approach_pose = self._apply_guidance_pose(
979
+ approach_pose,
980
+ observation_msg,
981
+ task,
982
+ guidance_context,
983
+ )
984
+ shaped_pose, wrench_feedback_gains, compensated_force_n = self._shape_pose(
985
+ approach_pose, observation_msg
986
+ )
987
+ shaped_pose_position_log = [
988
+ float(shaped_pose.position.x),
989
+ float(shaped_pose.position.y),
990
+ float(shaped_pose.position.z),
991
+ ]
992
+ action_accepted = bool(
993
+ move_robot(
994
+ motion_update=self.create_pose_motion_update(
995
+ shaped_pose,
996
+ wrench_feedback_gains=wrench_feedback_gains,
997
+ )
998
+ )
999
+ )
1000
+ if (
1001
+ phase_elapsed >= self.approach_min_sec
1002
+ and self._act_target_is_stable()
1003
+ and position_error <= self.align_position_tolerance_m
1004
+ and self._guidance_allows_align(guidance_context)
1005
+ ):
1006
+ self._set_phase("ALIGN", loop_now, reason="target_stable")
1007
+
1008
+ elif phase_now == "ALIGN":
1009
+ approach_pose = self._apply_position_offset(
1010
+ act_pose, self.approach_offset
1011
+ )
1012
+ approach_pose = self._apply_guidance_pose(
1013
+ approach_pose,
1014
+ observation_msg,
1015
+ task,
1016
+ guidance_context,
1017
+ )
1018
+ align_pose = self._interpolate_pose(
1019
+ current_pose,
1020
+ approach_pose,
1021
+ self.guard_position_smoothing_scale,
1022
+ )
1023
+ shaped_pose, wrench_feedback_gains, compensated_force_n = self._shape_pose(
1024
+ align_pose, observation_msg
1025
+ )
1026
+ shaped_pose_position_log = [
1027
+ float(shaped_pose.position.x),
1028
+ float(shaped_pose.position.y),
1029
+ float(shaped_pose.position.z),
1030
+ ]
1031
+ action_accepted = bool(
1032
+ move_robot(
1033
+ motion_update=self.create_pose_motion_update(
1034
+ shaped_pose,
1035
+ wrench_feedback_gains=wrench_feedback_gains,
1036
+ )
1037
+ )
1038
+ )
1039
+ align_ok = (
1040
+ self._act_target_is_stable()
1041
+ and xy_error <= self.align_xy_error_tolerance_m
1042
+ and angular_error <= self.align_angular_tolerance_rad
1043
+ and self._guidance_allows_guarded_insert(guidance_context)
1044
+ )
1045
+ if align_ok:
1046
+ if self._align_stable_since is None:
1047
+ self._align_stable_since = loop_now
1048
+ elif loop_now - self._align_stable_since >= self.settle_time_s:
1049
+ self._guard_direction = self._estimate_insert_direction(
1050
+ observation_msg, act_pose
1051
+ )
1052
+ self._guard_start_pos = current_pos.copy()
1053
+ self._best_guard_progress_m = 0.0
1054
+ self._set_phase(
1055
+ "GUARDED_INSERT",
1056
+ loop_now,
1057
+ reason="aligned",
1058
+ )
1059
+ else:
1060
+ self._align_stable_since = None
1061
+
1062
+ elif phase_now == "GUARDED_INSERT":
1063
+ if self._guard_direction is None:
1064
+ self._guard_direction = self._estimate_insert_direction(
1065
+ observation_msg, act_pose
1066
+ )
1067
+ if self._guard_start_pos is None:
1068
+ self._guard_start_pos = current_pos.copy()
1069
+
1070
+ step_m = max(
1071
+ 0.001,
1072
+ self.max_linear_speed_mps
1073
+ * self.control_period_s
1074
+ * self.insertion_speed_scale,
1075
+ )
1076
+ if (
1077
+ compensated_force_n is not None
1078
+ and compensated_force_n > self.guarded_insert_force_start_n
1079
+ ):
1080
+ ramp_span = max(
1081
+ self.guarded_insert_force_stop_n
1082
+ - self.guarded_insert_force_start_n,
1083
+ 1e-6,
1084
+ )
1085
+ ramp_scale = 1.0 - (
1086
+ (
1087
+ compensated_force_n
1088
+ - self.guarded_insert_force_start_n
1089
+ )
1090
+ / ramp_span
1091
+ )
1092
+ step_m *= float(np.clip(ramp_scale, 0.1, 1.0))
1093
+
1094
+ guard_target_pos = current_pos + self._guard_direction * step_m
1095
+ guard_pose = Pose(
1096
+ position=Point(
1097
+ x=float(guard_target_pos[0]),
1098
+ y=float(guard_target_pos[1]),
1099
+ z=float(guard_target_pos[2]),
1100
+ ),
1101
+ orientation=act_pose.orientation,
1102
+ )
1103
+ guard_pose = self._privileged_guard_pose_adjustment(
1104
+ guard_pose,
1105
+ observation_msg,
1106
+ task,
1107
+ )
1108
+ shaped_pose, wrench_feedback_gains, compensated_force_n = self._shape_pose(
1109
+ guard_pose, observation_msg
1110
+ )
1111
+ shaped_pose_position_log = [
1112
+ float(shaped_pose.position.x),
1113
+ float(shaped_pose.position.y),
1114
+ float(shaped_pose.position.z),
1115
+ ]
1116
+ action_accepted = bool(
1117
+ move_robot(
1118
+ motion_update=self.create_pose_motion_update(
1119
+ shaped_pose,
1120
+ wrench_feedback_gains=wrench_feedback_gains,
1121
+ )
1122
+ )
1123
+ )
1124
+ progress_m = float(
1125
+ np.dot(
1126
+ current_pos - self._guard_start_pos,
1127
+ self._guard_direction,
1128
+ )
1129
+ )
1130
+ self._best_guard_progress_m = max(
1131
+ self._best_guard_progress_m, progress_m
1132
+ )
1133
+ if (
1134
+ compensated_force_n is not None
1135
+ and compensated_force_n >= self.guarded_insert_force_stop_n
1136
+ ):
1137
+ if self._retries_used < self.max_retries:
1138
+ self._enter_retry(
1139
+ observation_msg,
1140
+ self._guard_direction,
1141
+ loop_now,
1142
+ reason="force_stop",
1143
+ )
1144
+ else:
1145
+ termination_reason = "force_stop"
1146
+ wrapper_returned_success = self._maybe_finish_without_event(
1147
+ "force_stop"
1148
+ )
1149
+ elif phase_elapsed >= self.max_guarded_insert_sec:
1150
+ if self._best_guard_progress_m < self.guard_progress_epsilon_m:
1151
+ if self._retries_used < self.max_retries:
1152
+ self._enter_retry(
1153
+ observation_msg,
1154
+ self._guard_direction,
1155
+ loop_now,
1156
+ reason="no_progress",
1157
+ )
1158
+ else:
1159
+ termination_reason = "no_progress"
1160
+ wrapper_returned_success = self._maybe_finish_without_event(
1161
+ "no_progress"
1162
+ )
1163
+ else:
1164
+ termination_reason = "guarded_insert_complete"
1165
+ wrapper_returned_success = self._maybe_finish_without_event(
1166
+ "guarded_insert_complete"
1167
+ )
1168
+
1169
+ elif phase_now == "RETRY_OR_FINISH":
1170
+ if self._retry_target_pose is None:
1171
+ termination_reason = "retry_missing_target"
1172
+ wrapper_returned_success = self._maybe_finish_without_event(
1173
+ "retry_missing_target"
1174
+ )
1175
+ else:
1176
+ shaped_pose, wrench_feedback_gains, compensated_force_n = self._shape_pose(
1177
+ self._retry_target_pose, observation_msg
1178
+ )
1179
+ shaped_pose_position_log = [
1180
+ float(shaped_pose.position.x),
1181
+ float(shaped_pose.position.y),
1182
+ float(shaped_pose.position.z),
1183
+ ]
1184
+ action_accepted = bool(
1185
+ move_robot(
1186
+ motion_update=self.create_pose_motion_update(
1187
+ shaped_pose,
1188
+ wrench_feedback_gains=wrench_feedback_gains,
1189
+ )
1190
+ )
1191
+ )
1192
+ if phase_elapsed >= self.settle_time_s:
1193
+ if self._retries_used <= self.max_retries:
1194
+ retry_phase = self._guidance_retry_phase(
1195
+ guidance_context
1196
+ )
1197
+ self._set_phase(
1198
+ retry_phase,
1199
+ loop_now,
1200
+ reason=f"retry_{self._retry_reason}",
1201
+ )
1202
+ else:
1203
+ termination_reason = "retry_budget_exhausted"
1204
+ wrapper_returned_success = self._maybe_finish_without_event(
1205
+ "retry_budget_exhausted"
1206
+ )
1207
+
1208
+ if not action_accepted and termination_reason is None:
1209
+ termination_reason = "move_robot_rejected"
1210
+ wrapper_returned_success = False
1211
+
1212
+ shaped_pose_valid = not any(np.isnan(value) for value in shaped_pose_position_log)
1213
+ if action_type == "pose_target":
1214
+ action_clipped = shaped_pose_valid and not np.allclose(
1215
+ np.asarray(pose_position, dtype=np.float64),
1216
+ np.asarray(shaped_pose_position_log, dtype=np.float64),
1217
+ atol=1e-6,
1218
+ )
1219
+ else:
1220
+ raw_linear = np.asarray(action[:3], dtype=np.float64)
1221
+ raw_angular = np.asarray(action[3:6], dtype=np.float64)
1222
+ action_clipped = (
1223
+ shaped_linear_log is not None
1224
+ and not np.allclose(
1225
+ raw_linear,
1226
+ np.asarray(shaped_linear_log, dtype=np.float64),
1227
+ atol=1e-6,
1228
+ )
1229
+ ) or (
1230
+ shaped_angular_log is not None
1231
+ and not np.allclose(
1232
+ raw_angular,
1233
+ np.asarray(shaped_angular_log, dtype=np.float64),
1234
+ atol=1e-6,
1235
+ )
1236
+ )
1237
+
1238
+ feedback = f"phase={self._phase}"
1239
+ if compensated_force_n is not None:
1240
+ feedback += f" force={compensated_force_n:.2f}N"
1241
+ if self._phase == "RETRY_OR_FINISH":
1242
+ feedback += f" retry_reason={self._retry_reason}"
1243
+ if guidance_summary:
1244
+ feedback += f" {guidance_summary}"
1245
+
1246
+ guidance_mode = None
1247
+ guidance_advisory_only = None
1248
+ guidance_applied = None
1249
+ guidance_would_apply = None
1250
+ guidance_ready_for_align = None
1251
+ guidance_ready_for_insert = None
1252
+ guidance_proposed_local_offset_m = None
1253
+ guidance_proposed_world_offset_m = None
1254
+ if guidance_context is not None:
1255
+ guidance_mode = guidance_context.get("vision_mode")
1256
+ guidance_advisory_only = guidance_context.get("advisory_only")
1257
+ guidance_applied = guidance_context.get("guidance_applied")
1258
+ guidance_would_apply = guidance_context.get("guidance_would_apply")
1259
+ guidance_ready_for_align = guidance_context.get("ready_for_align")
1260
+ guidance_ready_for_insert = guidance_context.get("ready_for_insert")
1261
+ guidance_proposed_local_offset_m = guidance_context.get(
1262
+ "proposed_local_offset_m"
1263
+ )
1264
+ guidance_proposed_world_offset_m = guidance_context.get(
1265
+ "proposed_world_offset_m"
1266
+ )
1267
+
1268
+ result = {
1269
+ "timestamp": timestamp,
1270
+ "action_id": action_id,
1271
+ "source": self._episode_source,
1272
+ "policy_route": self._active_policy_route,
1273
+ "action_type": action_type,
1274
+ "raw_action": action.astype(float).tolist(),
1275
+ "raw_linear": action[:3].astype(float).tolist(),
1276
+ "raw_angular": action[3:6].astype(float).tolist(),
1277
+ "pose_target_position": pose_position.astype(float).tolist()
1278
+ if action.shape[0] >= 9
1279
+ else None,
1280
+ "pose_target_quaternion": pose_quaternion,
1281
+ "shaped_linear": shaped_linear_log,
1282
+ "shaped_angular": shaped_angular_log,
1283
+ "shaped_pose_position": shaped_pose_position_log,
1284
+ "joint_target_norm": float(np.linalg.norm(joint_targets)),
1285
+ "wrench_feedback_gains": list(wrench_feedback_gains),
1286
+ "force_n": compensated_force_n,
1287
+ "max_force_n": self._max_force_seen_n,
1288
+ "action_accepted": action_accepted,
1289
+ "action_clipped": bool(action_clipped),
1290
+ "phase_before": phase_before,
1291
+ "phase_after": self._phase,
1292
+ "termination_reason": termination_reason,
1293
+ "wrapper_returned_success": wrapper_returned_success,
1294
+ "is_recovery": is_recovery,
1295
+ "guidance_summary": guidance_summary,
1296
+ "guidance_mode": guidance_mode,
1297
+ "guidance_advisory_only": guidance_advisory_only,
1298
+ "guidance_applied": guidance_applied,
1299
+ "guidance_would_apply": guidance_would_apply,
1300
+ "guidance_ready_for_align": guidance_ready_for_align,
1301
+ "guidance_ready_for_insert": guidance_ready_for_insert,
1302
+ "guidance_proposed_local_offset_m": guidance_proposed_local_offset_m,
1303
+ "guidance_proposed_world_offset_m": guidance_proposed_world_offset_m,
1304
+ "feedback": feedback,
1305
+ "should_terminate": wrapper_returned_success is not None,
1306
+ }
1307
+ result.update(self._guidance_result_fields(guidance_context))
1308
+ return result
1309
+
1310
+ def insert_cable(
1311
+ self,
1312
+ task: Task,
1313
+ get_observation: GetObservationCallback,
1314
+ move_robot: MoveRobotCallback,
1315
+ send_feedback: SendFeedbackCallback,
1316
+ **kwargs,
1317
+ ):
1318
+ self._activate_policy_bundle_for_task(task)
1319
+ self.policy.reset()
1320
+ self._insertion_event_seen = False
1321
+ self._last_insertion_event = ""
1322
+ self._recent_act_pose_positions.clear()
1323
+ self._phase = "APPROACH"
1324
+ self._phase_start_time = time.time()
1325
+ self._align_stable_since = None
1326
+ self._guard_direction = None
1327
+ self._guard_start_pos = None
1328
+ self._best_guard_progress_m = 0.0
1329
+ self._retry_target_pose = None
1330
+ self._retry_reason = ""
1331
+ self._retries_used = 0
1332
+ self._max_force_seen_n = 0.0
1333
+ self._reset_privileged_terminal_guidance()
1334
+ self._activate_phase_policy_bundle("APPROACH", reason="insert_start")
1335
+ self._begin_canonical_episode(task)
1336
+ self.get_logger().info(f"RunACTStaged.insert_cable() enter. Task: {task}")
1337
+
1338
+ start_time = time.time()
1339
+ inference_count = 0
1340
+
1341
+ while time.time() - start_time < 30.0:
1342
+ if self._insertion_event_seen:
1343
+ self.get_logger().info(
1344
+ "Insertion event observed; exiting success. "
1345
+ f"event={self._last_insertion_event!r} "
1346
+ f"max_force_seen_n={self._max_force_seen_n:.4f}"
1347
+ )
1348
+ self._finalize_canonical_episode(
1349
+ wrapper_returned_success=True,
1350
+ termination_reason="insertion_event",
1351
+ )
1352
+ return True
1353
+
1354
+ loop_start = time.time()
1355
+ observation_msg = get_observation()
1356
+ if observation_msg is None:
1357
+ self.get_logger().info("No observation received.")
1358
+ continue
1359
+
1360
+ self._set_active_runtime_context(
1361
+ observation_msg=observation_msg,
1362
+ task_msg=task,
1363
+ move_robot=move_robot,
1364
+ )
1365
+ policy_observation = self.get_policy_observation()
1366
+ self._write_policy_observation(policy_observation)
1367
+
1368
+ obs_tensors = self.prepare_observations(observation_msg, task)
1369
+ with torch.inference_mode():
1370
+ normalized_action = self.policy.select_action(obs_tensors)
1371
+
1372
+ if not torch.isfinite(normalized_action).all():
1373
+ bad_count = int((~torch.isfinite(normalized_action)).sum().item())
1374
+ self.get_logger().warning(
1375
+ f"Non-finite normalized ACT action detected: {bad_count}. Replacing with zeros."
1376
+ )
1377
+ normalized_action = torch.nan_to_num(normalized_action)
1378
+
1379
+ raw_action_tensor = (normalized_action * self.action_std) + self.action_mean
1380
+ action = raw_action_tensor[0].detach().cpu().numpy()
1381
+ if not np.isfinite(action).all():
1382
+ bad_count = int(np.size(action) - np.isfinite(action).sum())
1383
+ self.get_logger().warning(
1384
+ f"Non-finite unnormalized ACT action detected: {bad_count}. Replacing with zeros."
1385
+ )
1386
+ action = np.nan_to_num(action, nan=0.0, posinf=0.0, neginf=0.0)
1387
+ action_result = self.step(action)
1388
+ self._write_action_and_wrapper_output(
1389
+ observation=policy_observation,
1390
+ action_result=action_result,
1391
+ )
1392
+
1393
+ if self.log_every_n_steps > 0 and inference_count % self.log_every_n_steps == 0:
1394
+ self.get_logger().info(
1395
+ "ACT staged action "
1396
+ f"step={inference_count + 1} "
1397
+ f"phase={action_result.get('phase_after')} "
1398
+ f"raw_linear={action_result.get('raw_linear')} "
1399
+ f"raw_angular={action_result.get('raw_angular')} "
1400
+ f"shaped_linear={action_result.get('shaped_linear') if action_result.get('shaped_linear') is not None else 'n/a'} "
1401
+ f"shaped_angular={action_result.get('shaped_angular') if action_result.get('shaped_angular') is not None else 'n/a'} "
1402
+ f"pose_position={action_result.get('pose_target_position')} "
1403
+ f"shaped_pose_position={action_result.get('shaped_pose_position')} "
1404
+ f"joint_norm={float(action_result.get('joint_target_norm', 0.0)):.6f} "
1405
+ f"mode={self.command_mode} "
1406
+ f"force_n={action_result.get('force_n') if action_result.get('force_n') is not None else float('nan'):.4f} "
1407
+ f"max_force_n={self._max_force_seen_n:.4f} "
1408
+ f"gains={action_result.get('wrench_feedback_gains')} "
1409
+ f"retries_used={self._retries_used}/{self.max_retries} "
1410
+ f"insertion_event={self._insertion_event_seen}"
1411
+ )
1412
+
1413
+ send_feedback(str(action_result.get("feedback", f"phase={self._phase}")))
1414
+ if bool(action_result.get("should_terminate", False)):
1415
+ final_success = bool(action_result.get("wrapper_returned_success"))
1416
+ self._finalize_canonical_episode(
1417
+ wrapper_returned_success=final_success,
1418
+ termination_reason=str(action_result.get("termination_reason") or "terminated"),
1419
+ )
1420
+ return final_success
1421
+ inference_count += 1
1422
+
1423
+ elapsed = time.time() - loop_start
1424
+ time.sleep(max(0.0, self.control_period_s - elapsed))
1425
+
1426
+ final_success = self._maybe_finish_without_event("timeout")
1427
+ self._finalize_canonical_episode(
1428
+ wrapper_returned_success=final_success,
1429
+ termination_reason="timeout",
1430
+ )
1431
+ return final_success
policy/aic_example_policies/ros/RunACTStagedScriptedInsert.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RunACTStaged approach/align, then a scripted, ground-truth-free insertion.
2
+
3
+ The learned stages run unchanged, including the wrapper's guarded insert,
4
+ which pulls the plug onto the port axis but stalls ~13 mm above the seat.
5
+ When the wrapper would finish there, this policy takes over and descends
6
+ straight down in base_link from the stall pose at a slow, fixed rate. A
7
+ small circular wiggle helps the plug past the port lip; its radius grows only
8
+ while depth progress stalls. No port pose is read.
9
+ """
10
+
11
+ import math
12
+ import os
13
+ import time
14
+
15
+ import numpy as np
16
+ from geometry_msgs.msg import Point, Pose
17
+
18
+ from .RunACTStaged import RunACTStaged
19
+
20
+
21
+ def _env_float(name: str, default: float) -> float:
22
+ return float(os.environ.get(name, default))
23
+
24
+
25
+ class _HandOff(Exception):
26
+ """Raised inside the parent loop when the guarded insert gives up."""
27
+
28
+
29
+ class RunACTStagedScriptedInsert(RunACTStaged):
30
+
31
+ def __init__(self, parent_node):
32
+ super().__init__(parent_node)
33
+ self.insert_depth_m = _env_float("AIC_SCRIPTED_INSERT_DEPTH_M", 0.025)
34
+ self.insert_speed_mps = _env_float("AIC_SCRIPTED_INSERT_SPEED_MPS", 0.004)
35
+ self.insert_time_s = _env_float("AIC_SCRIPTED_INSERT_TIME_S", 15.0)
36
+ self.stop_force_n = _env_float("AIC_SCRIPTED_INSERT_STOP_FORCE_N", 15.0)
37
+ self.wiggle_start_m = _env_float("AIC_SCRIPTED_INSERT_WIGGLE_M", 0.0005)
38
+ self.wiggle_max_m = _env_float("AIC_SCRIPTED_INSERT_WIGGLE_MAX_M", 0.0025)
39
+ self.wiggle_hz = _env_float("AIC_SCRIPTED_INSERT_WIGGLE_HZ", 1.0)
40
+ self.period_s = _env_float("AIC_SCRIPTED_INSERT_PERIOD_S", 0.05)
41
+ # The learned stages run at 85 N/m; that is too soft to move a plug
42
+ # held on the port lip, so only the scripted finish runs stiffer.
43
+ self.insert_stiffness_diag = [
44
+ float(v) for v in os.environ.get(
45
+ "AIC_SCRIPTED_INSERT_STIFFNESS",
46
+ "400,400,400,85,85,85").split(",")]
47
+
48
+ def _maybe_finish_without_event(self, reason: str) -> bool:
49
+ result = super()._maybe_finish_without_event(reason)
50
+ if self._phase in ("GUARDED_INSERT", "RETRY_OR_FINISH"):
51
+ raise _HandOff()
52
+ return result
53
+
54
+ def insert_cable(self, task, get_observation, move_robot, send_feedback,
55
+ **kwargs):
56
+ try:
57
+ return super().insert_cable(
58
+ task, get_observation, move_robot, send_feedback, **kwargs)
59
+ except _HandOff:
60
+ return self._scripted_insert(get_observation, move_robot)
61
+
62
+ def _scripted_insert(self, get_observation, move_robot) -> bool:
63
+ observation = get_observation()
64
+ start = observation.controller_state.tcp_pose
65
+ start_xyz = np.array(
66
+ [start.position.x, start.position.y, start.position.z])
67
+ self.get_logger().info(
68
+ "Scripted insert hand-off at "
69
+ f"xyz={np.round(start_xyz, 4).tolist()} "
70
+ f"depth={self.insert_depth_m} speed={self.insert_speed_mps} "
71
+ f"stiffness={self.insert_stiffness_diag}")
72
+ self.control_stiffness_diag = self.insert_stiffness_diag
73
+ wiggle_m = self.wiggle_start_m
74
+ best_z = start_xyz[2]
75
+ last_gain_t = t0 = time.time()
76
+ reason = "time_limit"
77
+ while (now := time.time()) - t0 < self.insert_time_s:
78
+ if self._insertion_event_seen:
79
+ reason = "insertion_event"
80
+ break
81
+ observation = get_observation()
82
+ if observation is None:
83
+ continue
84
+ tcp_z = observation.controller_state.tcp_pose.position.z
85
+ if tcp_z < best_z - 0.0005:
86
+ best_z, last_gain_t = tcp_z, now
87
+ elif now - last_gain_t > 1.0:
88
+ wiggle_m = min(wiggle_m + 0.00025, self.wiggle_max_m)
89
+ last_gain_t = now
90
+ force_n = self._compensated_force_magnitude(observation)
91
+ if force_n is not None and force_n >= self.stop_force_n:
92
+ reason = "force_stop"
93
+ break
94
+ depth = min(self.insert_speed_mps * (now - t0), self.insert_depth_m)
95
+ phase = 2.0 * math.pi * self.wiggle_hz * (now - t0)
96
+ target = Pose(
97
+ position=Point(
98
+ x=float(start_xyz[0] + wiggle_m * math.cos(phase)),
99
+ y=float(start_xyz[1] + wiggle_m * math.sin(phase)),
100
+ z=float(start_xyz[2] - depth)),
101
+ orientation=start.orientation)
102
+ move_robot(motion_update=self.create_pose_motion_update(target))
103
+ time.sleep(max(0.0, self.period_s - (time.time() - now)))
104
+ self.get_logger().info(
105
+ f"Scripted insert done. reason={reason} "
106
+ f"descended={(start_xyz[2] - best_z) * 1000:.1f}mm "
107
+ f"final_wiggle={wiggle_m * 1000:.2f}mm")
108
+ self._finalize_canonical_episode(
109
+ wrapper_returned_success=True, termination_reason=reason)
110
+ return True
policy/aic_example_policies/ros/__init__.py ADDED
File without changes
policy/aic_example_policies/ros/canonical_episode_writer.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any, TextIO
8
+
9
+
10
+ SCHEMA_VERSION = "insertion_episode/v1"
11
+
12
+
13
+ def utc_now_iso() -> str:
14
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace(
15
+ "+00:00", "Z"
16
+ )
17
+
18
+
19
+ def sanitize_token(value: str) -> str:
20
+ token = re.sub(r"[^A-Za-z0-9_.-]+", "_", value.strip())
21
+ token = token.strip("._")
22
+ return token or "unknown"
23
+
24
+
25
+ def build_episode_id(run_name: str, task_id: str, start_time_s: float) -> str:
26
+ millis = int(round(start_time_s * 1000.0))
27
+ return (
28
+ f"{sanitize_token(run_name)}__{sanitize_token(task_id or 'task')}__{millis}"
29
+ )
30
+
31
+
32
+ class CanonicalEpisodeWriter:
33
+ """Write canonical insertion-harness episodes directly to disk."""
34
+
35
+ def __init__(
36
+ self,
37
+ *,
38
+ dataset_root: Path,
39
+ episode_id: str,
40
+ metadata: dict[str, Any],
41
+ ) -> None:
42
+ self.dataset_root = dataset_root.expanduser().resolve()
43
+ self.episode_id = sanitize_token(episode_id)
44
+ self.root = self.dataset_root / self.episode_id
45
+ self.observations_dir = self.root / "observations"
46
+ self.observations_dir.mkdir(parents=True, exist_ok=True)
47
+
48
+ self._streams: dict[str, TextIO] = {}
49
+ self._metadata_path = self.root / "metadata.json"
50
+ self._labels_path = self.root / "labels.json"
51
+ self._metrics_path = self.root / "metrics.json"
52
+ self.write_metadata(metadata)
53
+
54
+ def write_metadata(self, metadata: dict[str, Any]) -> None:
55
+ payload = dict(metadata)
56
+ payload.setdefault("schema_version", SCHEMA_VERSION)
57
+ payload.setdefault("episode_id", self.episode_id)
58
+ self._metadata_path.write_text(json.dumps(payload, indent=2) + "\n")
59
+
60
+ def _stream(self, relative_path: str) -> TextIO:
61
+ handle = self._streams.get(relative_path)
62
+ if handle is not None:
63
+ return handle
64
+ path = self.root / relative_path
65
+ path.parent.mkdir(parents=True, exist_ok=True)
66
+ handle = path.open("a", encoding="utf-8")
67
+ self._streams[relative_path] = handle
68
+ return handle
69
+
70
+ def append_jsonl(self, relative_path: str, row: dict[str, Any]) -> None:
71
+ handle = self._stream(relative_path)
72
+ handle.write(json.dumps(row, separators=(",", ":")) + "\n")
73
+ handle.flush()
74
+
75
+ def write_robot_state(self, row: dict[str, Any]) -> None:
76
+ self.append_jsonl("observations/robot_state.jsonl", row)
77
+
78
+ def write_action(self, row: dict[str, Any]) -> None:
79
+ self.append_jsonl("observations/actions.jsonl", row)
80
+
81
+ def write_force_torque(self, row: dict[str, Any]) -> None:
82
+ self.append_jsonl("observations/force_torque.jsonl", row)
83
+
84
+ def write_wrapper_output(self, row: dict[str, Any]) -> None:
85
+ self.append_jsonl("observations/wrapper_outputs.jsonl", row)
86
+
87
+ def write_cv_output(self, row: dict[str, Any]) -> None:
88
+ self.append_jsonl("observations/cv_outputs.jsonl", row)
89
+
90
+ def write_privileged_state(self, row: dict[str, Any]) -> None:
91
+ self.append_jsonl("observations/privileged_state.jsonl", row)
92
+
93
+ def finalize(
94
+ self,
95
+ *,
96
+ labels: dict[str, Any],
97
+ metrics: dict[str, Any] | None = None,
98
+ ) -> None:
99
+ self._labels_path.write_text(json.dumps(labels, indent=2) + "\n")
100
+ if metrics is not None:
101
+ self._metrics_path.write_text(json.dumps(metrics, indent=2) + "\n")
102
+ self.close()
103
+
104
+ def close(self) -> None:
105
+ for handle in self._streams.values():
106
+ handle.close()
107
+ self._streams.clear()
policy/aic_example_policies/ros/sfp_tuning_profiles.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+
6
+ SFP_GENTLE_REFERENCE_TUNINGS = frozenset(
7
+ {
8
+ "gentle_ref_pack_v1",
9
+ "reference_gentle_v1",
10
+ "sfp_gentle_ref_pack_v1",
11
+ }
12
+ )
13
+
14
+
15
+ def get_sfp_primitive_tuning_profile() -> str:
16
+ value = os.environ.get(
17
+ "AIC_ACT_SFP_PRIMITIVE_TUNING",
18
+ os.environ.get("AIC_ACT_SFP_PRIMITIVE_VARIANT", "default"),
19
+ )
20
+ return (value or "default").strip().lower() or "default"
21
+
22
+
23
+ def is_sfp_gentle_reference_tuning(profile: str | None = None) -> bool:
24
+ return (
25
+ get_sfp_primitive_tuning_profile() if profile is None else profile
26
+ ) in SFP_GENTLE_REFERENCE_TUNINGS
policy/aic_example_policies/ros/vision_target_features.py ADDED
@@ -0,0 +1,1549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import math
5
+ import os
6
+ import re
7
+ import time
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ if TYPE_CHECKING:
14
+ from aic_task_interfaces.msg import Task
15
+
16
+
17
+ VISION_FEATURE_NAMES = (
18
+ "vision.target_valid",
19
+ "vision.target_center_u_norm",
20
+ "vision.target_center_v_norm",
21
+ "vision.target_scale_norm",
22
+ "vision.target_bearing_x",
23
+ "vision.target_bearing_y",
24
+ "vision.segmentation_confidence",
25
+ "vision.selection_confidence",
26
+ )
27
+
28
+ TASK_TEXT_PATTERN = re.compile(
29
+ r"insert\s+(?P<cable_type>\S+)\s+cable\s+\S+\s+with\s+"
30
+ r"(?P<plug_type>\S+)\s+plug\s+\S+\s+into\s+"
31
+ r"(?P<port_type>\S+)\s+port\s+(?P<port_name>\S+)\s+on\s+module\s+"
32
+ r"(?P<target_module_name>\S+)",
33
+ flags=re.IGNORECASE,
34
+ )
35
+
36
+
37
+ def _env_float(name: str, default: float) -> float:
38
+ value = os.environ.get(name)
39
+ return float(value) if value is not None else float(default)
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class VisionTargetFeatures:
44
+ target_valid: float
45
+ target_center_u_norm: float
46
+ target_center_v_norm: float
47
+ target_scale_norm: float
48
+ target_bearing_x: float
49
+ target_bearing_y: float
50
+ segmentation_confidence: float
51
+ selection_confidence: float
52
+
53
+ @classmethod
54
+ def zeros(cls) -> "VisionTargetFeatures":
55
+ return cls(
56
+ target_valid=0.0,
57
+ target_center_u_norm=0.0,
58
+ target_center_v_norm=0.0,
59
+ target_scale_norm=0.0,
60
+ target_bearing_x=0.0,
61
+ target_bearing_y=0.0,
62
+ segmentation_confidence=0.0,
63
+ selection_confidence=0.0,
64
+ )
65
+
66
+ def as_dict(self) -> dict[str, float]:
67
+ return {
68
+ "vision.target_valid": self.target_valid,
69
+ "vision.target_center_u_norm": self.target_center_u_norm,
70
+ "vision.target_center_v_norm": self.target_center_v_norm,
71
+ "vision.target_scale_norm": self.target_scale_norm,
72
+ "vision.target_bearing_x": self.target_bearing_x,
73
+ "vision.target_bearing_y": self.target_bearing_y,
74
+ "vision.segmentation_confidence": self.segmentation_confidence,
75
+ "vision.selection_confidence": self.selection_confidence,
76
+ }
77
+
78
+ def to_array(self) -> np.ndarray:
79
+ return np.array(
80
+ [
81
+ self.target_valid,
82
+ self.target_center_u_norm,
83
+ self.target_center_v_norm,
84
+ self.target_scale_norm,
85
+ self.target_bearing_x,
86
+ self.target_bearing_y,
87
+ self.segmentation_confidence,
88
+ self.selection_confidence,
89
+ ],
90
+ dtype=np.float32,
91
+ )
92
+
93
+
94
+ @dataclass(frozen=True, slots=True)
95
+ class _Candidate:
96
+ score: float
97
+ center_u: float
98
+ center_v: float
99
+ area_frac: float
100
+ fill_ratio: float
101
+ aspect_ratio: float
102
+ bbox_xyxy: tuple[float, float, float, float]
103
+ bbox_wh: tuple[float, float]
104
+ angle_rad: float
105
+ uncertainty_px: tuple[float, float]
106
+ major_endpoints: tuple[tuple[float, float], tuple[float, float]]
107
+
108
+
109
+ @dataclass(frozen=True, slots=True)
110
+ class CVTargetObservation:
111
+ visible: bool
112
+ class_name: str
113
+ slot: str
114
+ center_px: tuple[float, float]
115
+ confidence: float
116
+ orientation_rad: float
117
+ uncertainty_px: tuple[float, float]
118
+ bbox_xyxy: tuple[float, float, float, float]
119
+ scale_norm: float
120
+
121
+ @classmethod
122
+ def empty(
123
+ cls,
124
+ *,
125
+ class_name: str = "target",
126
+ slot: str = "unknown",
127
+ ) -> "CVTargetObservation":
128
+ return cls(
129
+ visible=False,
130
+ class_name=class_name,
131
+ slot=slot,
132
+ center_px=(0.0, 0.0),
133
+ confidence=0.0,
134
+ orientation_rad=0.0,
135
+ uncertainty_px=(0.0, 0.0),
136
+ bbox_xyxy=(0.0, 0.0, 0.0, 0.0),
137
+ scale_norm=0.0,
138
+ )
139
+
140
+ def to_dict(self) -> dict[str, Any]:
141
+ return {
142
+ "visible": bool(self.visible),
143
+ "class": self.class_name,
144
+ "slot": self.slot,
145
+ "center_px": [float(self.center_px[0]), float(self.center_px[1])],
146
+ "confidence": float(self.confidence),
147
+ "orientation_rad": float(self.orientation_rad),
148
+ "uncertainty_px": [
149
+ float(self.uncertainty_px[0]),
150
+ float(self.uncertainty_px[1]),
151
+ ],
152
+ "bbox": [
153
+ float(self.bbox_xyxy[0]),
154
+ float(self.bbox_xyxy[1]),
155
+ float(self.bbox_xyxy[2]),
156
+ float(self.bbox_xyxy[3]),
157
+ ],
158
+ "scale_norm": float(self.scale_norm),
159
+ }
160
+
161
+
162
+ @dataclass(frozen=True, slots=True)
163
+ class CVPlugObservation:
164
+ visible: bool
165
+ class_name: str
166
+ tip_px: tuple[float, float]
167
+ confidence: float
168
+ orientation_rad: float
169
+ uncertainty_px: tuple[float, float]
170
+ bbox_xyxy: tuple[float, float, float, float]
171
+ scale_norm: float
172
+
173
+ @classmethod
174
+ def empty(cls, *, class_name: str = "plug") -> "CVPlugObservation":
175
+ return cls(
176
+ visible=False,
177
+ class_name=class_name,
178
+ tip_px=(0.0, 0.0),
179
+ confidence=0.0,
180
+ orientation_rad=0.0,
181
+ uncertainty_px=(0.0, 0.0),
182
+ bbox_xyxy=(0.0, 0.0, 0.0, 0.0),
183
+ scale_norm=0.0,
184
+ )
185
+
186
+ def to_dict(self) -> dict[str, Any]:
187
+ return {
188
+ "visible": bool(self.visible),
189
+ "class": self.class_name,
190
+ "tip_px": [float(self.tip_px[0]), float(self.tip_px[1])],
191
+ "confidence": float(self.confidence),
192
+ "orientation_rad": float(self.orientation_rad),
193
+ "uncertainty_px": [
194
+ float(self.uncertainty_px[0]),
195
+ float(self.uncertainty_px[1]),
196
+ ],
197
+ "bbox": [
198
+ float(self.bbox_xyxy[0]),
199
+ float(self.bbox_xyxy[1]),
200
+ float(self.bbox_xyxy[2]),
201
+ float(self.bbox_xyxy[3]),
202
+ ],
203
+ "scale_norm": float(self.scale_norm),
204
+ }
205
+
206
+
207
+ @dataclass(frozen=True, slots=True)
208
+ class CVVisualError:
209
+ du: float
210
+ dv: float
211
+ dtheta_rad: float
212
+
213
+ @classmethod
214
+ def zeros(cls) -> "CVVisualError":
215
+ return cls(du=0.0, dv=0.0, dtheta_rad=0.0)
216
+
217
+ def to_dict(self) -> dict[str, float]:
218
+ return {
219
+ "du": float(self.du),
220
+ "dv": float(self.dv),
221
+ "dtheta_rad": float(self.dtheta_rad),
222
+ }
223
+
224
+
225
+ @dataclass(frozen=True, slots=True)
226
+ class CVPoseEstimate:
227
+ valid: bool
228
+ method: str
229
+ target_translation_camera_m: tuple[float, float, float]
230
+ lateral_error_m: tuple[float, float]
231
+ yaw_error_rad: float
232
+ range_m: float
233
+ reprojection_error_px: float
234
+ confidence: float
235
+ reason: str
236
+
237
+ @classmethod
238
+ def invalid(cls, reason: str) -> "CVPoseEstimate":
239
+ return cls(
240
+ valid=False,
241
+ method="unavailable",
242
+ target_translation_camera_m=(0.0, 0.0, 0.0),
243
+ lateral_error_m=(0.0, 0.0),
244
+ yaw_error_rad=0.0,
245
+ range_m=0.0,
246
+ reprojection_error_px=float("inf"),
247
+ confidence=0.0,
248
+ reason=reason,
249
+ )
250
+
251
+ def to_dict(self) -> dict[str, Any]:
252
+ return {
253
+ "valid": bool(self.valid),
254
+ "method": self.method,
255
+ "target_translation_camera_m": [
256
+ float(self.target_translation_camera_m[0]),
257
+ float(self.target_translation_camera_m[1]),
258
+ float(self.target_translation_camera_m[2]),
259
+ ],
260
+ "lateral_error_m": [
261
+ float(self.lateral_error_m[0]),
262
+ float(self.lateral_error_m[1]),
263
+ ],
264
+ "yaw_error_rad": float(self.yaw_error_rad),
265
+ "range_m": float(self.range_m),
266
+ "reprojection_error_px": float(self.reprojection_error_px),
267
+ "confidence": float(self.confidence),
268
+ "reason": self.reason,
269
+ }
270
+
271
+
272
+ @dataclass(frozen=True, slots=True)
273
+ class CVObservation:
274
+ timestamp: float
275
+ frame_id: int
276
+ camera: str
277
+ target: CVTargetObservation
278
+ plug: CVPlugObservation
279
+ visual_error: CVVisualError
280
+ stale: bool
281
+ latency_ms: float
282
+ ambiguous: bool
283
+ confidence_drop: bool
284
+ segmentation_confidence: float
285
+ selection_confidence: float
286
+ pose_estimate: CVPoseEstimate | None = None
287
+
288
+ def to_dict(self) -> dict[str, Any]:
289
+ return {
290
+ "timestamp": float(self.timestamp),
291
+ "frame_id": int(self.frame_id),
292
+ "camera": self.camera,
293
+ "target": self.target.to_dict(),
294
+ "plug": self.plug.to_dict(),
295
+ "visual_error": self.visual_error.to_dict(),
296
+ "stale": bool(self.stale),
297
+ "latency_ms": float(self.latency_ms),
298
+ "ambiguous": bool(self.ambiguous),
299
+ "confidence_drop": bool(self.confidence_drop),
300
+ "segmentation_confidence": float(self.segmentation_confidence),
301
+ "selection_confidence": float(self.selection_confidence),
302
+ "pose_estimate": (
303
+ self.pose_estimate.to_dict()
304
+ if self.pose_estimate is not None
305
+ else CVPoseEstimate.invalid("not_computed").to_dict()
306
+ ),
307
+ "detections": self._to_detections(),
308
+ }
309
+
310
+ def to_harness_row(
311
+ self,
312
+ *,
313
+ phase: str | None = None,
314
+ stage: str | None = None,
315
+ supervisor_phase: str | None = None,
316
+ ) -> dict[str, Any]:
317
+ row = self.to_dict()
318
+ if phase:
319
+ row["phase"] = phase
320
+ if stage:
321
+ row["stage"] = stage
322
+ if supervisor_phase:
323
+ row["supervisor_phase"] = supervisor_phase
324
+ return row
325
+
326
+ def _to_detections(self) -> list[dict[str, Any]]:
327
+ detections: list[dict[str, Any]] = []
328
+ if self.target.visible:
329
+ detections.append(
330
+ {
331
+ "class": self.target.class_name,
332
+ "bbox": [
333
+ float(self.target.bbox_xyxy[0]),
334
+ float(self.target.bbox_xyxy[1]),
335
+ float(self.target.bbox_xyxy[2]),
336
+ float(self.target.bbox_xyxy[3]),
337
+ ],
338
+ "confidence": float(self.target.confidence),
339
+ "orientation_rad": float(self.target.orientation_rad),
340
+ "uncertainty_px": [
341
+ float(self.target.uncertainty_px[0]),
342
+ float(self.target.uncertainty_px[1]),
343
+ ],
344
+ "slot": self.target.slot,
345
+ "keypoints": {
346
+ "center": [
347
+ float(self.target.center_px[0]),
348
+ float(self.target.center_px[1]),
349
+ ]
350
+ },
351
+ }
352
+ )
353
+ if self.plug.visible:
354
+ detections.append(
355
+ {
356
+ "class": self.plug.class_name,
357
+ "bbox": [
358
+ float(self.plug.bbox_xyxy[0]),
359
+ float(self.plug.bbox_xyxy[1]),
360
+ float(self.plug.bbox_xyxy[2]),
361
+ float(self.plug.bbox_xyxy[3]),
362
+ ],
363
+ "confidence": float(self.plug.confidence),
364
+ "orientation_rad": float(self.plug.orientation_rad),
365
+ "uncertainty_px": [
366
+ float(self.plug.uncertainty_px[0]),
367
+ float(self.plug.uncertainty_px[1]),
368
+ ],
369
+ "keypoints": {
370
+ "tip": [float(self.plug.tip_px[0]), float(self.plug.tip_px[1])]
371
+ },
372
+ }
373
+ )
374
+ return detections
375
+
376
+ def to_vision_target_features(
377
+ self,
378
+ *,
379
+ image_width: float,
380
+ image_height: float,
381
+ valid_threshold: float,
382
+ ) -> VisionTargetFeatures:
383
+ center_u_norm = 0.0
384
+ center_v_norm = 0.0
385
+ bearing_x = 0.0
386
+ bearing_y = 0.0
387
+ if image_width > 1.0 and image_height > 1.0:
388
+ center_u_norm = float(
389
+ np.clip(self.target.center_px[0] / max(1.0, image_width - 1.0), 0.0, 1.0)
390
+ )
391
+ center_v_norm = float(
392
+ np.clip(self.target.center_px[1] / max(1.0, image_height - 1.0), 0.0, 1.0)
393
+ )
394
+ bearing_x = float(
395
+ np.clip(
396
+ (self.target.center_px[0] - (0.5 * (image_width - 1.0)))
397
+ / max(1.0, 0.5 * (image_width - 1.0)),
398
+ -1.0,
399
+ 1.0,
400
+ )
401
+ )
402
+ bearing_y = float(
403
+ np.clip(
404
+ (self.target.center_px[1] - (0.5 * (image_height - 1.0)))
405
+ / max(1.0, 0.5 * (image_height - 1.0)),
406
+ -1.0,
407
+ 1.0,
408
+ )
409
+ )
410
+
411
+ target_valid = (
412
+ 1.0
413
+ if self.target.visible
414
+ and not self.stale
415
+ and self.segmentation_confidence >= float(valid_threshold)
416
+ else 0.0
417
+ )
418
+ return VisionTargetFeatures(
419
+ target_valid=target_valid,
420
+ target_center_u_norm=center_u_norm,
421
+ target_center_v_norm=center_v_norm,
422
+ target_scale_norm=float(np.clip(self.target.scale_norm, 0.0, 1.0)),
423
+ target_bearing_x=bearing_x,
424
+ target_bearing_y=bearing_y,
425
+ segmentation_confidence=float(
426
+ np.clip(self.segmentation_confidence, 0.0, 1.0)
427
+ ),
428
+ selection_confidence=float(np.clip(self.selection_confidence, 0.0, 1.0)),
429
+ )
430
+
431
+
432
+ class ClassicalPortPoseEstimator:
433
+ """Estimate live plug-to-port geometry from center-camera keypoints.
434
+
435
+ This is deliberately conservative: it does not require privileged TF and it
436
+ falls back to calibrated-FOV pinhole geometry when camera_info is absent.
437
+ A tiny diagonal Kalman update smooths the local lateral/yaw/range estimate
438
+ without hiding large jumps behind an overfit replay template.
439
+ """
440
+
441
+ def __init__(
442
+ self,
443
+ *,
444
+ horizontal_fov_deg: float | None = None,
445
+ vertical_fov_deg: float | None = None,
446
+ min_confidence: float | None = None,
447
+ max_reprojection_error_px: float | None = None,
448
+ ):
449
+ self._horizontal_fov_deg = float(
450
+ horizontal_fov_deg
451
+ if horizontal_fov_deg is not None
452
+ else _env_float("AIC_CLASSICAL_CENTER_HFOV_DEG", 70.0)
453
+ )
454
+ self._vertical_fov_deg = float(
455
+ vertical_fov_deg
456
+ if vertical_fov_deg is not None
457
+ else _env_float("AIC_CLASSICAL_CENTER_VFOV_DEG", 55.0)
458
+ )
459
+ self._min_confidence = float(
460
+ min_confidence
461
+ if min_confidence is not None
462
+ else _env_float("AIC_CLASSICAL_POSE_MIN_CONFIDENCE", 0.12)
463
+ )
464
+ self._max_reprojection_error_px = float(
465
+ max_reprojection_error_px
466
+ if max_reprojection_error_px is not None
467
+ else _env_float("AIC_CLASSICAL_POSE_MAX_REPROJECTION_PX", 45.0)
468
+ )
469
+ self._range_min_m = _env_float("AIC_CLASSICAL_POSE_MIN_RANGE_M", 0.04)
470
+ self._range_max_m = _env_float("AIC_CLASSICAL_POSE_MAX_RANGE_M", 0.55)
471
+ self._process_noise = np.array([4.0e-6, 4.0e-6, 2.0e-4, 4.0e-5], dtype=np.float64)
472
+ self._measurement_noise = np.array([2.5e-5, 2.5e-5, 2.0e-3, 2.5e-4], dtype=np.float64)
473
+ self._state: np.ndarray | None = None
474
+ self._covariance: np.ndarray | None = None
475
+
476
+ def reset(self) -> None:
477
+ self._state = None
478
+ self._covariance = None
479
+
480
+ def estimate(
481
+ self,
482
+ *,
483
+ target: CVTargetObservation,
484
+ plug: CVPlugObservation,
485
+ visual_error: CVVisualError,
486
+ image_width: int,
487
+ image_height: int,
488
+ ) -> CVPoseEstimate:
489
+ if image_width <= 1 or image_height <= 1:
490
+ return CVPoseEstimate.invalid("invalid_image_size")
491
+ if not target.visible:
492
+ return CVPoseEstimate.invalid("target_not_visible")
493
+
494
+ bbox_width_px = max(1.0, float(target.bbox_xyxy[2] - target.bbox_xyxy[0]))
495
+ bbox_height_px = max(1.0, float(target.bbox_xyxy[3] - target.bbox_xyxy[1]))
496
+ fx, fy, cx, cy = self._camera_intrinsics(image_width, image_height)
497
+ physical_width_m, physical_height_m = self._target_dimensions_m(target.class_name)
498
+ range_from_width = fx * physical_width_m / bbox_width_px
499
+ range_from_height = fy * physical_height_m / bbox_height_px
500
+ range_m = float(
501
+ np.clip(
502
+ 0.5 * (range_from_width + range_from_height),
503
+ self._range_min_m,
504
+ self._range_max_m,
505
+ )
506
+ )
507
+
508
+ tx_m = ((float(target.center_px[0]) - cx) / max(fx, 1.0e-6)) * range_m
509
+ ty_m = ((float(target.center_px[1]) - cy) / max(fy, 1.0e-6)) * range_m
510
+ target_translation = (float(tx_m), float(ty_m), float(range_m))
511
+
512
+ if not plug.visible:
513
+ confidence = 0.5 * float(target.confidence)
514
+ return CVPoseEstimate(
515
+ valid=confidence >= self._min_confidence,
516
+ method="bbox_range_target_only",
517
+ target_translation_camera_m=target_translation,
518
+ lateral_error_m=(0.0, 0.0),
519
+ yaw_error_rad=0.0,
520
+ range_m=range_m,
521
+ reprojection_error_px=0.5 * (float(target.uncertainty_px[0]) + float(target.uncertainty_px[1])),
522
+ confidence=confidence,
523
+ reason="plug_not_visible",
524
+ )
525
+
526
+ lateral_x_m = (float(visual_error.du) / max(fx, 1.0e-6)) * range_m
527
+ lateral_y_m = (float(visual_error.dv) / max(fy, 1.0e-6)) * range_m
528
+ yaw_error_rad = float(_wrap_half_turn(visual_error.dtheta_rad))
529
+ confidence = float(
530
+ np.clip(
531
+ math.sqrt(max(target.confidence, 0.0) * max(plug.confidence, 0.0)),
532
+ 0.0,
533
+ 1.0,
534
+ )
535
+ )
536
+ reprojection_error_px = self._pseudo_reprojection_error_px(
537
+ target=target,
538
+ plug=plug,
539
+ range_from_width=range_from_width,
540
+ range_from_height=range_from_height,
541
+ )
542
+ valid = bool(
543
+ confidence >= self._min_confidence
544
+ and reprojection_error_px <= self._max_reprojection_error_px
545
+ )
546
+ if not valid:
547
+ reason = (
548
+ "low_confidence"
549
+ if confidence < self._min_confidence
550
+ else "high_reprojection_error"
551
+ )
552
+ return CVPoseEstimate.invalid(reason)
553
+
554
+ filtered = self._kalman_update(
555
+ np.array([lateral_x_m, lateral_y_m, yaw_error_rad, range_m], dtype=np.float64),
556
+ confidence=confidence,
557
+ )
558
+ return CVPoseEstimate(
559
+ valid=True,
560
+ method="bbox_range_keypoint_kalman",
561
+ target_translation_camera_m=target_translation,
562
+ lateral_error_m=(float(filtered[0]), float(filtered[1])),
563
+ yaw_error_rad=float(filtered[2]),
564
+ range_m=float(filtered[3]),
565
+ reprojection_error_px=float(reprojection_error_px),
566
+ confidence=confidence,
567
+ reason="ok",
568
+ )
569
+
570
+ def _camera_intrinsics(self, image_width: int, image_height: int) -> tuple[float, float, float, float]:
571
+ fx_env = os.environ.get("AIC_CLASSICAL_CENTER_FX_PX")
572
+ fy_env = os.environ.get("AIC_CLASSICAL_CENTER_FY_PX")
573
+ cx_env = os.environ.get("AIC_CLASSICAL_CENTER_CX_PX")
574
+ cy_env = os.environ.get("AIC_CLASSICAL_CENTER_CY_PX")
575
+ fx = (
576
+ float(fx_env)
577
+ if fx_env is not None
578
+ else float(image_width) / (2.0 * math.tan(math.radians(self._horizontal_fov_deg) * 0.5))
579
+ )
580
+ fy = (
581
+ float(fy_env)
582
+ if fy_env is not None
583
+ else float(image_height) / (2.0 * math.tan(math.radians(self._vertical_fov_deg) * 0.5))
584
+ )
585
+ cx = float(cx_env) if cx_env is not None else 0.5 * float(image_width - 1)
586
+ cy = float(cy_env) if cy_env is not None else 0.5 * float(image_height - 1)
587
+ return fx, fy, cx, cy
588
+
589
+ @staticmethod
590
+ def _target_dimensions_m(class_name: str) -> tuple[float, float]:
591
+ normalized = (class_name or "").lower()
592
+ if "sfp" in normalized:
593
+ return (
594
+ _env_float("AIC_CLASSICAL_SFP_PORT_WIDTH_M", 0.016),
595
+ _env_float("AIC_CLASSICAL_SFP_PORT_HEIGHT_M", 0.010),
596
+ )
597
+ if "lc" in normalized:
598
+ return (
599
+ _env_float("AIC_CLASSICAL_LC_PORT_WIDTH_M", 0.010),
600
+ _env_float("AIC_CLASSICAL_LC_PORT_HEIGHT_M", 0.007),
601
+ )
602
+ return (
603
+ _env_float("AIC_CLASSICAL_SC_PORT_WIDTH_M", 0.012),
604
+ _env_float("AIC_CLASSICAL_SC_PORT_HEIGHT_M", 0.008),
605
+ )
606
+
607
+ @staticmethod
608
+ def _pseudo_reprojection_error_px(
609
+ *,
610
+ target: CVTargetObservation,
611
+ plug: CVPlugObservation,
612
+ range_from_width: float,
613
+ range_from_height: float,
614
+ ) -> float:
615
+ size_consistency_px = abs(range_from_width - range_from_height) * 20.0
616
+ uncertainty_px = 0.25 * (
617
+ float(target.uncertainty_px[0])
618
+ + float(target.uncertainty_px[1])
619
+ + float(plug.uncertainty_px[0])
620
+ + float(plug.uncertainty_px[1])
621
+ )
622
+ return float(max(0.0, size_consistency_px + uncertainty_px))
623
+
624
+ def _kalman_update(self, measurement: np.ndarray, *, confidence: float) -> np.ndarray:
625
+ if self._state is None or self._covariance is None:
626
+ self._state = measurement.astype(np.float64)
627
+ self._covariance = np.array([1.0e-4, 1.0e-4, 1.0e-2, 1.0e-3], dtype=np.float64)
628
+ return self._state.copy()
629
+
630
+ self._covariance = self._covariance + self._process_noise
631
+ noise_scale = 1.0 / max(float(confidence) * float(confidence), 0.05)
632
+ measurement_noise = self._measurement_noise * noise_scale
633
+ kalman_gain = self._covariance / (self._covariance + measurement_noise)
634
+ innovation = measurement - self._state
635
+ innovation[2] = _wrap_half_turn(float(innovation[2]))
636
+ self._state = self._state + (kalman_gain * innovation)
637
+ self._state[2] = _wrap_half_turn(float(self._state[2]))
638
+ self._covariance = (1.0 - kalman_gain) * self._covariance
639
+ return self._state.copy()
640
+
641
+
642
+ @dataclass(slots=True)
643
+ class _TrackState:
644
+ visible: bool = False
645
+ center_px: tuple[float, float] = (0.0, 0.0)
646
+ orientation_rad: float = 0.0
647
+ confidence: float = 0.0
648
+ uncertainty_px: tuple[float, float] = (0.0, 0.0)
649
+ bbox_xyxy: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)
650
+ scale_norm: float = 0.0
651
+ timestamp: float = float("-inf")
652
+
653
+
654
+ def _extract_suffix_index(name: str) -> int:
655
+ match = re.search(r"(\d+)$", name or "")
656
+ return int(match.group(1)) if match else -1
657
+
658
+
659
+ def _wrap_half_turn(angle_rad: float) -> float:
660
+ wrapped = (angle_rad + math.pi) % (2.0 * math.pi) - math.pi
661
+ if wrapped <= -0.5 * math.pi:
662
+ wrapped += math.pi
663
+ elif wrapped > 0.5 * math.pi:
664
+ wrapped -= math.pi
665
+ return float(wrapped)
666
+
667
+
668
+ def _name_prefix_token(name: str | None) -> str | None:
669
+ if not isinstance(name, str) or not name:
670
+ return None
671
+ token = name.split("_", 1)[0].strip().lower()
672
+ return token or None
673
+
674
+
675
+ def _angle_delta(target_rad: float, source_rad: float) -> float:
676
+ return _wrap_half_turn(float(target_rad) - float(source_rad))
677
+
678
+
679
+ def _candidate_scale_norm(
680
+ candidate: _Candidate,
681
+ *,
682
+ min_area_frac: float,
683
+ max_area_frac: float,
684
+ ) -> float:
685
+ return float(
686
+ np.clip(
687
+ math.sqrt(candidate.area_frac / max(min_area_frac, 1e-8))
688
+ / math.sqrt(max_area_frac / max(min_area_frac, 1e-8)),
689
+ 0.0,
690
+ 1.0,
691
+ )
692
+ )
693
+
694
+
695
+ def _task_value(task_msg: Any | None, task_hint: dict[str, Any] | None, key: str) -> Any:
696
+ if task_hint is not None and key in task_hint:
697
+ return task_hint[key]
698
+ if task_msg is not None and hasattr(task_msg, key):
699
+ return getattr(task_msg, key)
700
+ return None
701
+
702
+
703
+ def parse_task_text(task_text: str | None) -> dict[str, Any]:
704
+ if not isinstance(task_text, str) or not task_text.strip():
705
+ return {}
706
+ match = TASK_TEXT_PATTERN.search(task_text.strip())
707
+ if match is None:
708
+ return {"task_text": task_text}
709
+
710
+ payload = match.groupdict()
711
+ payload["task_text"] = task_text
712
+ payload["target_module_index"] = _extract_suffix_index(
713
+ payload.get("target_module_name", "")
714
+ )
715
+ payload["target_port_index"] = _extract_suffix_index(payload.get("port_name", ""))
716
+ return payload
717
+
718
+
719
+ def _slot_name(task_msg: Any | None, task_hint: dict[str, Any] | None) -> str:
720
+ module_name = _task_value(task_msg, task_hint, "target_module_name")
721
+ if isinstance(module_name, str) and module_name:
722
+ return module_name
723
+
724
+ module_index = _task_value(task_msg, task_hint, "task.target_module_index")
725
+ if module_index is None:
726
+ module_index = _extract_suffix_index(
727
+ str(_task_value(task_msg, task_hint, "target_module_name") or "")
728
+ )
729
+ try:
730
+ module_index_int = int(float(module_index))
731
+ except (TypeError, ValueError):
732
+ module_index_int = -1
733
+ if module_index_int >= 0:
734
+ return f"nic_card_mount_{module_index_int}"
735
+ return "unknown"
736
+
737
+
738
+ def _port_class_name(task_msg: Any | None, task_hint: dict[str, Any] | None) -> str:
739
+ port_type = _task_value(task_msg, task_hint, "port_type")
740
+ if isinstance(port_type, str) and port_type:
741
+ return f"{port_type}_port"
742
+
743
+ port_type_id = _task_value(task_msg, task_hint, "task.port_type_id")
744
+ port_type_map = {1: "sc_port", 2: "sfp_port"}
745
+ try:
746
+ if port_type_id is not None:
747
+ mapped = port_type_map.get(int(float(port_type_id)))
748
+ if mapped is not None:
749
+ return mapped
750
+ except (TypeError, ValueError):
751
+ pass
752
+ inferred = _name_prefix_token(
753
+ str(_task_value(task_msg, task_hint, "port_name") or "")
754
+ )
755
+ if inferred is not None:
756
+ return f"{inferred}_port"
757
+ return "target_port"
758
+
759
+
760
+ def _plug_class_name(task_msg: Any | None, task_hint: dict[str, Any] | None) -> str:
761
+ plug_type = _task_value(task_msg, task_hint, "plug_type")
762
+ if isinstance(plug_type, str) and plug_type:
763
+ return f"{plug_type}_plug"
764
+
765
+ plug_type_id = _task_value(task_msg, task_hint, "task.plug_type_id")
766
+ plug_type_map = {1: "sc_plug", 2: "sfp_plug", 3: "lc_plug"}
767
+ try:
768
+ if plug_type_id is not None:
769
+ mapped = plug_type_map.get(int(float(plug_type_id)))
770
+ if mapped is not None:
771
+ return mapped
772
+ except (TypeError, ValueError):
773
+ pass
774
+ inferred = _name_prefix_token(str(_task_value(task_msg, task_hint, "plug_name") or ""))
775
+ if inferred is not None:
776
+ return f"{inferred}_plug"
777
+ return "plug"
778
+
779
+
780
+ def build_task_grounding_metadata(
781
+ *,
782
+ task_msg: Any | None = None,
783
+ task_hint: dict[str, Any] | None = None,
784
+ task_text: str | None = None,
785
+ episode_id: str | None = None,
786
+ frame_idx: int | None = None,
787
+ success: bool | None = None,
788
+ failure_type: str | None = None,
789
+ ) -> dict[str, Any]:
790
+ parsed_text = parse_task_text(task_text)
791
+
792
+ port_name_value = _task_value(task_msg, task_hint, "port_name")
793
+ if not isinstance(port_name_value, str) or not port_name_value:
794
+ port_name_value = parsed_text.get("port_name") or "unknown"
795
+
796
+ target_module_name = _task_value(task_msg, task_hint, "target_module_name")
797
+ if not isinstance(target_module_name, str) or not target_module_name:
798
+ target_module_name = parsed_text.get("target_module_name") or _slot_name(
799
+ task_msg, task_hint
800
+ )
801
+
802
+ cable_type = _task_value(task_msg, task_hint, "cable_type")
803
+ if not isinstance(cable_type, str) or not cable_type:
804
+ cable_type = parsed_text.get("cable_type") or "unknown"
805
+
806
+ plug_type = _task_value(task_msg, task_hint, "plug_type")
807
+ if not isinstance(plug_type, str) or not plug_type:
808
+ plug_type = parsed_text.get("plug_type")
809
+ if not isinstance(plug_type, str) or not plug_type:
810
+ plug_type = _plug_class_name(task_msg, task_hint).removesuffix("_plug")
811
+
812
+ port_type = _task_value(task_msg, task_hint, "port_type")
813
+ if not isinstance(port_type, str) or not port_type:
814
+ port_type = parsed_text.get("port_type")
815
+ if not isinstance(port_type, str) or not port_type:
816
+ port_type = _port_class_name(task_msg, task_hint).removesuffix("_port")
817
+
818
+ target_module_index = _task_value(task_msg, task_hint, "task.target_module_index")
819
+ if target_module_index is None and task_hint is not None:
820
+ target_module_index = task_hint.get("target_module_index")
821
+ if target_module_index is None:
822
+ target_module_index = parsed_text.get("target_module_index")
823
+ if target_module_index is None:
824
+ target_module_index = _extract_suffix_index(target_module_name)
825
+
826
+ target_port_index = _task_value(task_msg, task_hint, "task.target_port_index")
827
+ if target_port_index is None and task_hint is not None:
828
+ target_port_index = task_hint.get("target_port_index")
829
+ if target_port_index is None:
830
+ target_port_index = parsed_text.get("target_port_index")
831
+ if target_port_index is None:
832
+ target_port_index = _extract_suffix_index(port_name_value)
833
+
834
+ try:
835
+ target_module_index = int(float(target_module_index))
836
+ except (TypeError, ValueError):
837
+ target_module_index = -1
838
+
839
+ try:
840
+ target_port_index = int(float(target_port_index))
841
+ except (TypeError, ValueError):
842
+ target_port_index = -1
843
+
844
+ task_text_value = task_text if isinstance(task_text, str) and task_text else None
845
+ if task_text_value is None and parsed_text.get("task_text"):
846
+ task_text_value = str(parsed_text["task_text"])
847
+
848
+ return {
849
+ "task_text": task_text_value,
850
+ "cable_class": cable_type,
851
+ "plug_class": f"{plug_type}_plug" if plug_type != "unknown" else "plug",
852
+ "target_class": f"{port_type}_port" if port_type != "unknown" else "target_port",
853
+ "target_slot": target_module_name,
854
+ "target_module_name": target_module_name,
855
+ "target_module_index": target_module_index,
856
+ "target_port_index": target_port_index,
857
+ "port_name": port_name_value,
858
+ "episode_id": episode_id,
859
+ "frame_idx": frame_idx,
860
+ "success": success,
861
+ "failure_type": failure_type,
862
+ }
863
+
864
+
865
+ def ros_image_to_rgb(raw_img) -> np.ndarray:
866
+ channels = 4 if raw_img.encoding in {"rgba8", "bgra8"} else 3
867
+ image_np = np.frombuffer(raw_img.data, dtype=np.uint8).reshape(
868
+ raw_img.height, raw_img.width, channels
869
+ )
870
+
871
+ if raw_img.encoding == "rgb8":
872
+ return image_np
873
+ if raw_img.encoding == "bgr8":
874
+ return image_np[:, :, ::-1]
875
+ if raw_img.encoding == "rgba8":
876
+ return image_np[:, :, :3]
877
+ if raw_img.encoding == "bgra8":
878
+ return image_np[:, :, :3][:, :, ::-1]
879
+
880
+ # Fall back to assuming RGB layout when the encoding is omitted.
881
+ return image_np[:, :, :3]
882
+
883
+
884
+ class CenterPortFeatureExtractor:
885
+ """Extract compact target-port features from the center RGB image.
886
+
887
+ The implementation is intentionally lightweight and deterministic so the
888
+ feature contract can stabilize before a learned segmenter replaces it.
889
+ """
890
+
891
+ def __init__(
892
+ self,
893
+ *,
894
+ min_area_frac: float = 2e-4,
895
+ max_area_frac: float = 1.5e-1,
896
+ valid_threshold: float = 0.35,
897
+ ):
898
+ self._min_area_frac = float(min_area_frac)
899
+ self._max_area_frac = float(max_area_frac)
900
+ self._valid_threshold = float(valid_threshold)
901
+
902
+ def extract(
903
+ self,
904
+ *,
905
+ raw_img=None,
906
+ image_rgb: np.ndarray | None = None,
907
+ task_msg: Any | None = None,
908
+ task_hint: dict[str, float] | None = None,
909
+ ) -> VisionTargetFeatures:
910
+ if image_rgb is None:
911
+ if raw_img is None:
912
+ return VisionTargetFeatures.zeros()
913
+ image_rgb = ros_image_to_rgb(raw_img)
914
+
915
+ if image_rgb is None or image_rgb.size == 0:
916
+ return VisionTargetFeatures.zeros()
917
+
918
+ height, width = image_rgb.shape[:2]
919
+ if height <= 1 or width <= 1:
920
+ return VisionTargetFeatures.zeros()
921
+
922
+ mask = self._build_mask(image_rgb)
923
+ candidates = self._extract_candidates(mask)
924
+ if not candidates:
925
+ return VisionTargetFeatures.zeros()
926
+
927
+ candidate, selection_conf = self._select_candidate(
928
+ candidates,
929
+ task_msg=task_msg,
930
+ task_hint=task_hint,
931
+ )
932
+ target_valid = 1.0 if candidate.score >= self._valid_threshold else 0.0
933
+ center_u_norm = float(np.clip(candidate.center_u / max(1.0, width - 1), 0.0, 1.0))
934
+ center_v_norm = float(np.clip(candidate.center_v / max(1.0, height - 1), 0.0, 1.0))
935
+ scale_norm = _candidate_scale_norm(
936
+ candidate,
937
+ min_area_frac=self._min_area_frac,
938
+ max_area_frac=self._max_area_frac,
939
+ )
940
+ bearing_x = float(
941
+ np.clip((candidate.center_u - (0.5 * (width - 1))) / max(1.0, 0.5 * (width - 1)), -1.0, 1.0)
942
+ )
943
+ bearing_y = float(
944
+ np.clip((candidate.center_v - (0.5 * (height - 1))) / max(1.0, 0.5 * (height - 1)), -1.0, 1.0)
945
+ )
946
+
947
+ return VisionTargetFeatures(
948
+ target_valid=target_valid,
949
+ target_center_u_norm=center_u_norm,
950
+ target_center_v_norm=center_v_norm,
951
+ target_scale_norm=scale_norm,
952
+ target_bearing_x=bearing_x,
953
+ target_bearing_y=bearing_y,
954
+ segmentation_confidence=float(np.clip(candidate.score, 0.0, 1.0)),
955
+ selection_confidence=float(np.clip(selection_conf, 0.0, 1.0)),
956
+ )
957
+
958
+ def _build_mask(self, image_rgb: np.ndarray) -> np.ndarray:
959
+ gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
960
+ blurred = cv2.GaussianBlur(gray, (5, 5), 0)
961
+ adaptive = cv2.adaptiveThreshold(
962
+ blurred,
963
+ 255,
964
+ cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
965
+ cv2.THRESH_BINARY_INV,
966
+ 31,
967
+ 5,
968
+ )
969
+
970
+ hsv = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2HSV)
971
+ dark_mask = cv2.inRange(
972
+ hsv,
973
+ np.array((0, 0, 0), dtype=np.uint8),
974
+ np.array((180, 255, 110), dtype=np.uint8),
975
+ )
976
+ mask = cv2.bitwise_and(adaptive, dark_mask)
977
+
978
+ kernel = np.ones((3, 3), dtype=np.uint8)
979
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
980
+ mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
981
+ return mask
982
+
983
+ def _extract_candidates(self, mask: np.ndarray) -> list[_Candidate]:
984
+ height, width = mask.shape[:2]
985
+ image_area = float(height * width)
986
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
987
+
988
+ candidates: list[_Candidate] = []
989
+ for contour in contours:
990
+ area_px = float(cv2.contourArea(contour))
991
+ area_frac = area_px / max(image_area, 1.0)
992
+ if area_frac < self._min_area_frac or area_frac > self._max_area_frac:
993
+ continue
994
+
995
+ x, y, w, h = cv2.boundingRect(contour)
996
+ rect_area = float(max(1, w * h))
997
+ fill_ratio = area_px / rect_area
998
+ if fill_ratio < 0.2:
999
+ continue
1000
+
1001
+ aspect_ratio = float(w) / float(max(1, h))
1002
+ if aspect_ratio < 0.2 or aspect_ratio > 5.0:
1003
+ continue
1004
+
1005
+ moments = cv2.moments(contour)
1006
+ if moments["m00"] == 0.0:
1007
+ continue
1008
+
1009
+ rect = cv2.minAreaRect(contour)
1010
+ rect_w = float(max(rect[1][0], 1.0))
1011
+ rect_h = float(max(rect[1][1], 1.0))
1012
+ angle_deg = float(rect[2] + (0.0 if rect_w >= rect_h else 90.0))
1013
+ angle_rad = _wrap_half_turn(math.radians(angle_deg))
1014
+ contour_points = contour.reshape(-1, 2).astype(np.float64)
1015
+ direction = np.array(
1016
+ [math.cos(angle_rad), math.sin(angle_rad)], dtype=np.float64
1017
+ )
1018
+ projections = contour_points @ direction
1019
+ endpoint_a = contour_points[int(np.argmin(projections))]
1020
+ endpoint_b = contour_points[int(np.argmax(projections))]
1021
+
1022
+ center_u = moments["m10"] / moments["m00"]
1023
+ center_v = moments["m01"] / moments["m00"]
1024
+ center_dx = (center_u - (0.5 * (width - 1))) / max(1.0, 0.5 * (width - 1))
1025
+ center_dy = (center_v - (0.5 * (height - 1))) / max(1.0, 0.5 * (height - 1))
1026
+ center_distance = math.sqrt((center_dx * center_dx) + (center_dy * center_dy))
1027
+ center_score = max(0.0, 1.0 - min(1.0, center_distance))
1028
+ fill_score = max(0.0, min(1.0, fill_ratio / 0.75))
1029
+ area_score = max(0.0, min(1.0, area_frac / 0.02))
1030
+ aspect_score = max(
1031
+ 0.0,
1032
+ 1.0 - min(1.0, abs(math.log(max(aspect_ratio, 1e-6))) / math.log(4.0)),
1033
+ )
1034
+
1035
+ score = (
1036
+ 0.35 * center_score
1037
+ + 0.25 * fill_score
1038
+ + 0.20 * area_score
1039
+ + 0.20 * aspect_score
1040
+ )
1041
+ candidates.append(
1042
+ _Candidate(
1043
+ score=float(score),
1044
+ center_u=float(center_u),
1045
+ center_v=float(center_v),
1046
+ area_frac=float(area_frac),
1047
+ fill_ratio=float(fill_ratio),
1048
+ aspect_ratio=float(aspect_ratio),
1049
+ bbox_xyxy=(
1050
+ float(x),
1051
+ float(y),
1052
+ float(x + w),
1053
+ float(y + h),
1054
+ ),
1055
+ bbox_wh=(float(w), float(h)),
1056
+ angle_rad=float(angle_rad),
1057
+ uncertainty_px=(
1058
+ float(1.0 + (0.5 * max(1.0, w) * (1.0 - score))),
1059
+ float(1.0 + (0.5 * max(1.0, h) * (1.0 - score))),
1060
+ ),
1061
+ major_endpoints=(
1062
+ (float(endpoint_a[0]), float(endpoint_a[1])),
1063
+ (float(endpoint_b[0]), float(endpoint_b[1])),
1064
+ ),
1065
+ )
1066
+ )
1067
+
1068
+ candidates.sort(key=lambda item: item.score, reverse=True)
1069
+ return candidates
1070
+
1071
+ def _select_candidate(
1072
+ self,
1073
+ candidates: list[_Candidate],
1074
+ *,
1075
+ task_msg: Any | None,
1076
+ task_hint: dict[str, float] | None,
1077
+ ) -> tuple[_Candidate, float]:
1078
+ if len(candidates) == 1:
1079
+ return candidates[0], 1.0
1080
+
1081
+ desired_index = self._desired_candidate_index(task_msg, task_hint)
1082
+ if desired_index is not None and 0 <= desired_index < len(candidates):
1083
+ ordered = sorted(candidates, key=lambda item: item.center_u)
1084
+ chosen = ordered[desired_index]
1085
+ score_gap = max(0.0, min(1.0, chosen.score - ordered[0].score + 0.5))
1086
+ return chosen, max(0.45, score_gap)
1087
+
1088
+ top = candidates[0]
1089
+ runner_up = candidates[1]
1090
+ gap = max(0.0, min(1.0, 0.5 + (top.score - runner_up.score)))
1091
+ return top, gap
1092
+
1093
+ @staticmethod
1094
+ def _desired_candidate_index(
1095
+ task_msg: Any | None,
1096
+ task_hint: dict[str, float] | None,
1097
+ ) -> int | None:
1098
+ if task_hint is not None:
1099
+ port_index = int(task_hint.get("task.target_port_index", -1.0))
1100
+ if port_index >= 0:
1101
+ return port_index
1102
+
1103
+ module_index = int(task_hint.get("task.target_module_index", -1.0))
1104
+ if module_index >= 0:
1105
+ return module_index
1106
+
1107
+ if task_msg is None:
1108
+ return None
1109
+
1110
+ port_index = _extract_suffix_index(task_msg.port_name)
1111
+ if port_index >= 0:
1112
+ return port_index
1113
+
1114
+ module_index = _extract_suffix_index(task_msg.target_module_name)
1115
+ if module_index >= 0:
1116
+ return module_index
1117
+
1118
+ return None
1119
+
1120
+
1121
+ class CenterPortCVPipeline:
1122
+ """Stateful CV pipeline that emits control-relevant, harness-ready observations."""
1123
+
1124
+ def __init__(
1125
+ self,
1126
+ *,
1127
+ extractor: CenterPortFeatureExtractor | None = None,
1128
+ camera_name: str = "wrist",
1129
+ tracking_alpha: float = 0.40,
1130
+ jump_alpha: float = 0.15,
1131
+ max_tracking_jump_px: float = 80.0,
1132
+ stale_after_s: float = 0.25,
1133
+ plug_min_confidence: float = 0.20,
1134
+ ):
1135
+ self._extractor = extractor or CenterPortFeatureExtractor()
1136
+ self._camera_name = camera_name
1137
+ self._tracking_alpha = float(tracking_alpha)
1138
+ self._jump_alpha = float(jump_alpha)
1139
+ self._max_tracking_jump_px = float(max_tracking_jump_px)
1140
+ self._stale_after_s = float(stale_after_s)
1141
+ self._plug_min_confidence = float(plug_min_confidence)
1142
+ self._target_track = _TrackState()
1143
+ self._plug_track = _TrackState()
1144
+ self._pose_estimator = ClassicalPortPoseEstimator()
1145
+ self._latest_observation: CVObservation | None = None
1146
+ self._frame_counter = -1
1147
+
1148
+ def reset(self) -> None:
1149
+ self._target_track = _TrackState()
1150
+ self._plug_track = _TrackState()
1151
+ self._pose_estimator.reset()
1152
+ self._latest_observation = None
1153
+ self._frame_counter = -1
1154
+
1155
+ def process_frame(
1156
+ self,
1157
+ frame=None,
1158
+ task_info: Any | None = None,
1159
+ *,
1160
+ raw_img=None,
1161
+ image_rgb: np.ndarray | None = None,
1162
+ task_msg: Any | None = None,
1163
+ task_hint: dict[str, Any] | None = None,
1164
+ timestamp: float | None = None,
1165
+ frame_id: int | None = None,
1166
+ camera: str | None = None,
1167
+ ) -> CVObservation:
1168
+ start = time.perf_counter()
1169
+ if frame is not None:
1170
+ if image_rgb is None and isinstance(frame, np.ndarray):
1171
+ image_rgb = frame
1172
+ elif raw_img is None:
1173
+ raw_img = frame
1174
+
1175
+ if task_info is not None:
1176
+ if isinstance(task_info, dict):
1177
+ task_hint = task_info
1178
+ else:
1179
+ task_msg = task_info
1180
+
1181
+ if image_rgb is None:
1182
+ if raw_img is None:
1183
+ raise ValueError("process_frame requires frame, raw_img, or image_rgb")
1184
+ image_rgb = ros_image_to_rgb(raw_img)
1185
+
1186
+ if timestamp is None:
1187
+ timestamp = time.time()
1188
+ if frame_id is None:
1189
+ self._frame_counter += 1
1190
+ frame_id = self._frame_counter
1191
+
1192
+ height, width = image_rgb.shape[:2]
1193
+ mask = self._extractor._build_mask(image_rgb)
1194
+ candidates = self._extractor._extract_candidates(mask)
1195
+
1196
+ target_class = _port_class_name(task_msg, task_hint)
1197
+ plug_class = _plug_class_name(task_msg, task_hint)
1198
+ slot_name = _slot_name(task_msg, task_hint)
1199
+
1200
+ target_candidate = None
1201
+ selection_conf = 0.0
1202
+ segmentation_conf = 0.0
1203
+ if candidates:
1204
+ target_candidate, selection_conf = self._extractor._select_candidate(
1205
+ candidates,
1206
+ task_msg=task_msg,
1207
+ task_hint=task_hint,
1208
+ )
1209
+ segmentation_conf = float(np.clip(target_candidate.score, 0.0, 1.0))
1210
+ target_confidence = 0.0
1211
+ if target_candidate is not None:
1212
+ target_confidence = float(
1213
+ np.clip(
1214
+ math.sqrt(max(segmentation_conf, 0.0) * max(selection_conf, 0.0)),
1215
+ 0.0,
1216
+ 1.0,
1217
+ )
1218
+ )
1219
+
1220
+ plug_candidate, plug_confidence = self._select_plug_candidate(
1221
+ candidates,
1222
+ target_candidate=target_candidate,
1223
+ )
1224
+
1225
+ target_visible_raw = (
1226
+ target_candidate is not None
1227
+ and target_candidate.score >= self._extractor._valid_threshold
1228
+ )
1229
+ plug_visible_raw = (
1230
+ plug_candidate is not None and plug_confidence >= self._plug_min_confidence
1231
+ )
1232
+
1233
+ target_obs, target_stale, target_conf_drop = self._track_target(
1234
+ candidate=target_candidate,
1235
+ visible_raw=target_visible_raw,
1236
+ confidence=target_confidence,
1237
+ timestamp=float(timestamp),
1238
+ class_name=target_class,
1239
+ slot=slot_name,
1240
+ )
1241
+ plug_obs, plug_stale, plug_conf_drop = self._track_plug(
1242
+ candidate=plug_candidate,
1243
+ target_center_px=target_obs.center_px,
1244
+ visible_raw=plug_visible_raw,
1245
+ confidence=plug_confidence,
1246
+ timestamp=float(timestamp),
1247
+ class_name=plug_class,
1248
+ )
1249
+
1250
+ ambiguous = bool(
1251
+ len(candidates) > 1
1252
+ and (selection_conf < 0.65 or (candidates[0].score - candidates[1].score) < 0.08)
1253
+ )
1254
+ stale = bool(target_stale or plug_stale)
1255
+ confidence_drop = bool(target_conf_drop or plug_conf_drop)
1256
+
1257
+ if target_obs.visible and plug_obs.visible:
1258
+ visual_error = CVVisualError(
1259
+ du=float(plug_obs.tip_px[0] - target_obs.center_px[0]),
1260
+ dv=float(plug_obs.tip_px[1] - target_obs.center_px[1]),
1261
+ dtheta_rad=float(
1262
+ _angle_delta(plug_obs.orientation_rad, target_obs.orientation_rad)
1263
+ ),
1264
+ )
1265
+ else:
1266
+ visual_error = CVVisualError.zeros()
1267
+
1268
+ pose_estimate = self._pose_estimator.estimate(
1269
+ target=target_obs,
1270
+ plug=plug_obs,
1271
+ visual_error=visual_error,
1272
+ image_width=int(width),
1273
+ image_height=int(height),
1274
+ )
1275
+
1276
+ observation = CVObservation(
1277
+ timestamp=float(timestamp),
1278
+ frame_id=int(frame_id),
1279
+ camera=camera or self._camera_name,
1280
+ target=target_obs,
1281
+ plug=plug_obs,
1282
+ visual_error=visual_error,
1283
+ stale=stale,
1284
+ latency_ms=float((time.perf_counter() - start) * 1000.0),
1285
+ ambiguous=ambiguous,
1286
+ confidence_drop=confidence_drop,
1287
+ segmentation_confidence=segmentation_conf,
1288
+ selection_confidence=float(np.clip(selection_conf, 0.0, 1.0)),
1289
+ pose_estimate=pose_estimate,
1290
+ )
1291
+ self._latest_observation = observation
1292
+ return observation
1293
+
1294
+ def get_latest_observation(self) -> CVObservation | None:
1295
+ return self._latest_observation
1296
+
1297
+ def get_latest_harness_row(self) -> dict[str, Any] | None:
1298
+ if self._latest_observation is None:
1299
+ return None
1300
+ return self._latest_observation.to_harness_row()
1301
+
1302
+ def _select_plug_candidate(
1303
+ self,
1304
+ candidates: list[_Candidate],
1305
+ *,
1306
+ target_candidate: _Candidate | None,
1307
+ ) -> tuple[_Candidate | None, float]:
1308
+ remaining = [
1309
+ candidate
1310
+ for candidate in candidates
1311
+ if target_candidate is None or candidate.bbox_xyxy != target_candidate.bbox_xyxy
1312
+ ]
1313
+ if not remaining:
1314
+ return None, 0.0
1315
+
1316
+ target_center = None
1317
+ if target_candidate is not None:
1318
+ target_center = np.array(
1319
+ [target_candidate.center_u, target_candidate.center_v], dtype=np.float64
1320
+ )
1321
+
1322
+ best_candidate = None
1323
+ best_score = float("-inf")
1324
+ second_score = float("-inf")
1325
+ for candidate in remaining:
1326
+ candidate_score = candidate.score
1327
+ if target_center is not None:
1328
+ distance_px = float(
1329
+ np.linalg.norm(
1330
+ np.array([candidate.center_u, candidate.center_v], dtype=np.float64)
1331
+ - target_center
1332
+ )
1333
+ )
1334
+ proximity_bonus = max(0.0, 1.0 - min(1.0, distance_px / 220.0))
1335
+ candidate_score += 0.10 * proximity_bonus
1336
+ elongation_bonus = min(
1337
+ 1.0, abs(math.log(max(candidate.aspect_ratio, 1.0e-6))) / math.log(6.0)
1338
+ )
1339
+ candidate_score += 0.08 * elongation_bonus
1340
+
1341
+ if candidate_score > best_score:
1342
+ second_score = best_score
1343
+ best_score = candidate_score
1344
+ best_candidate = candidate
1345
+ elif candidate_score > second_score:
1346
+ second_score = candidate_score
1347
+
1348
+ if best_candidate is None:
1349
+ return None, 0.0
1350
+
1351
+ gap = 1.0 if second_score == float("-inf") else max(0.0, min(1.0, 0.5 + (best_score - second_score)))
1352
+ confidence = float(np.clip(math.sqrt(max(best_candidate.score, 0.0) * gap), 0.0, 1.0))
1353
+ return best_candidate, confidence
1354
+
1355
+ def _smooth_track(
1356
+ self,
1357
+ track: _TrackState,
1358
+ *,
1359
+ center_px: tuple[float, float],
1360
+ orientation_rad: float,
1361
+ confidence: float,
1362
+ uncertainty_px: tuple[float, float],
1363
+ bbox_xyxy: tuple[float, float, float, float],
1364
+ scale_norm: float,
1365
+ timestamp: float,
1366
+ ) -> tuple[_TrackState, bool]:
1367
+ confidence_drop = False
1368
+ if not track.visible:
1369
+ updated = _TrackState(
1370
+ visible=True,
1371
+ center_px=center_px,
1372
+ orientation_rad=orientation_rad,
1373
+ confidence=confidence,
1374
+ uncertainty_px=uncertainty_px,
1375
+ bbox_xyxy=bbox_xyxy,
1376
+ scale_norm=scale_norm,
1377
+ timestamp=timestamp,
1378
+ )
1379
+ return updated, confidence_drop
1380
+
1381
+ jump_px = math.dist(center_px, track.center_px)
1382
+ alpha = self._tracking_alpha if jump_px <= self._max_tracking_jump_px else self._jump_alpha
1383
+ smoothed_center = (
1384
+ float((alpha * center_px[0]) + ((1.0 - alpha) * track.center_px[0])),
1385
+ float((alpha * center_px[1]) + ((1.0 - alpha) * track.center_px[1])),
1386
+ )
1387
+ smoothed_orientation = _wrap_half_turn(
1388
+ track.orientation_rad + (alpha * _angle_delta(orientation_rad, track.orientation_rad))
1389
+ )
1390
+ smoothed_confidence = float(
1391
+ np.clip((alpha * confidence) + ((1.0 - alpha) * track.confidence), 0.0, 1.0)
1392
+ )
1393
+ confidence_drop = confidence < max(0.0, track.confidence - 0.20)
1394
+ smoothed_uncertainty = (
1395
+ float((alpha * uncertainty_px[0]) + ((1.0 - alpha) * track.uncertainty_px[0])),
1396
+ float((alpha * uncertainty_px[1]) + ((1.0 - alpha) * track.uncertainty_px[1])),
1397
+ )
1398
+ smoothed_bbox = tuple(
1399
+ float((alpha * curr) + ((1.0 - alpha) * prev))
1400
+ for curr, prev in zip(bbox_xyxy, track.bbox_xyxy)
1401
+ )
1402
+ updated = _TrackState(
1403
+ visible=True,
1404
+ center_px=smoothed_center,
1405
+ orientation_rad=smoothed_orientation,
1406
+ confidence=smoothed_confidence,
1407
+ uncertainty_px=smoothed_uncertainty,
1408
+ bbox_xyxy=smoothed_bbox,
1409
+ scale_norm=float((alpha * scale_norm) + ((1.0 - alpha) * track.scale_norm)),
1410
+ timestamp=timestamp,
1411
+ )
1412
+ return updated, confidence_drop
1413
+
1414
+ def _stale_track(self, track: _TrackState, *, timestamp: float) -> _TrackState | None:
1415
+ if not track.visible:
1416
+ return None
1417
+ age_s = float(timestamp - track.timestamp)
1418
+ if age_s < 0.0 or age_s > self._stale_after_s:
1419
+ return None
1420
+ decay = max(0.0, 1.0 - (age_s / max(self._stale_after_s, 1.0e-6)))
1421
+ return _TrackState(
1422
+ visible=True,
1423
+ center_px=track.center_px,
1424
+ orientation_rad=track.orientation_rad,
1425
+ confidence=float(np.clip(track.confidence * decay, 0.0, 1.0)),
1426
+ uncertainty_px=(
1427
+ float(track.uncertainty_px[0] + (4.0 * age_s)),
1428
+ float(track.uncertainty_px[1] + (4.0 * age_s)),
1429
+ ),
1430
+ bbox_xyxy=track.bbox_xyxy,
1431
+ scale_norm=track.scale_norm,
1432
+ timestamp=track.timestamp,
1433
+ )
1434
+
1435
+ def _track_target(
1436
+ self,
1437
+ *,
1438
+ candidate: _Candidate | None,
1439
+ visible_raw: bool,
1440
+ confidence: float,
1441
+ timestamp: float,
1442
+ class_name: str,
1443
+ slot: str,
1444
+ ) -> tuple[CVTargetObservation, bool, bool]:
1445
+ confidence_drop = False
1446
+ stale = False
1447
+ if candidate is not None and visible_raw:
1448
+ scale_norm = _candidate_scale_norm(
1449
+ candidate,
1450
+ min_area_frac=self._extractor._min_area_frac,
1451
+ max_area_frac=self._extractor._max_area_frac,
1452
+ )
1453
+ self._target_track, confidence_drop = self._smooth_track(
1454
+ self._target_track,
1455
+ center_px=(candidate.center_u, candidate.center_v),
1456
+ orientation_rad=candidate.angle_rad,
1457
+ confidence=confidence,
1458
+ uncertainty_px=candidate.uncertainty_px,
1459
+ bbox_xyxy=candidate.bbox_xyxy,
1460
+ scale_norm=scale_norm,
1461
+ timestamp=timestamp,
1462
+ )
1463
+ else:
1464
+ carried = self._stale_track(self._target_track, timestamp=timestamp)
1465
+ if carried is None:
1466
+ self._target_track = _TrackState()
1467
+ else:
1468
+ self._target_track = carried
1469
+ stale = True
1470
+
1471
+ if not self._target_track.visible:
1472
+ return CVTargetObservation.empty(class_name=class_name, slot=slot), stale, confidence_drop
1473
+
1474
+ observation = CVTargetObservation(
1475
+ visible=True,
1476
+ class_name=class_name,
1477
+ slot=slot,
1478
+ center_px=self._target_track.center_px,
1479
+ confidence=self._target_track.confidence,
1480
+ orientation_rad=self._target_track.orientation_rad,
1481
+ uncertainty_px=self._target_track.uncertainty_px,
1482
+ bbox_xyxy=self._target_track.bbox_xyxy,
1483
+ scale_norm=self._target_track.scale_norm,
1484
+ )
1485
+ return observation, stale, confidence_drop
1486
+
1487
+ def _track_plug(
1488
+ self,
1489
+ *,
1490
+ candidate: _Candidate | None,
1491
+ target_center_px: tuple[float, float],
1492
+ visible_raw: bool,
1493
+ confidence: float,
1494
+ timestamp: float,
1495
+ class_name: str,
1496
+ ) -> tuple[CVPlugObservation, bool, bool]:
1497
+ confidence_drop = False
1498
+ stale = False
1499
+ if candidate is not None and visible_raw:
1500
+ tip_px = self._plug_tip(candidate, target_center_px)
1501
+ scale_norm = _candidate_scale_norm(
1502
+ candidate,
1503
+ min_area_frac=self._extractor._min_area_frac,
1504
+ max_area_frac=self._extractor._max_area_frac,
1505
+ )
1506
+ self._plug_track, confidence_drop = self._smooth_track(
1507
+ self._plug_track,
1508
+ center_px=tip_px,
1509
+ orientation_rad=candidate.angle_rad,
1510
+ confidence=confidence,
1511
+ uncertainty_px=candidate.uncertainty_px,
1512
+ bbox_xyxy=candidate.bbox_xyxy,
1513
+ scale_norm=scale_norm,
1514
+ timestamp=timestamp,
1515
+ )
1516
+ else:
1517
+ carried = self._stale_track(self._plug_track, timestamp=timestamp)
1518
+ if carried is None:
1519
+ self._plug_track = _TrackState()
1520
+ else:
1521
+ self._plug_track = carried
1522
+ stale = True
1523
+
1524
+ if not self._plug_track.visible:
1525
+ return CVPlugObservation.empty(class_name=class_name), stale, confidence_drop
1526
+
1527
+ observation = CVPlugObservation(
1528
+ visible=True,
1529
+ class_name=class_name,
1530
+ tip_px=self._plug_track.center_px,
1531
+ confidence=self._plug_track.confidence,
1532
+ orientation_rad=self._plug_track.orientation_rad,
1533
+ uncertainty_px=self._plug_track.uncertainty_px,
1534
+ bbox_xyxy=self._plug_track.bbox_xyxy,
1535
+ scale_norm=self._plug_track.scale_norm,
1536
+ )
1537
+ return observation, stale, confidence_drop
1538
+
1539
+ @staticmethod
1540
+ def _plug_tip(
1541
+ candidate: _Candidate,
1542
+ target_center_px: tuple[float, float],
1543
+ ) -> tuple[float, float]:
1544
+ endpoint_a, endpoint_b = candidate.major_endpoints
1545
+ if target_center_px == (0.0, 0.0):
1546
+ return endpoint_a if endpoint_a[1] <= endpoint_b[1] else endpoint_b
1547
+ distance_a = math.dist(endpoint_a, target_center_px)
1548
+ distance_b = math.dist(endpoint_b, target_center_px)
1549
+ return endpoint_a if distance_a <= distance_b else endpoint_b
policy_env.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ AIC_ACT_STAGED_MAX_GUARDED_INSERT_SEC=5
2
+ AIC_ACT_POLICY_PATH_APPROACH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
3
+ AIC_ACT_POLICY_PATH_RETRY_OR_FINISH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_retry_or_finish/2026-05-06_00-51-10/checkpoints/010000/pretrained_model
4
+ AIC_ACT_POLICY_PATH_ALIGN=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_align/2026-05-06_00-41-13/checkpoints/010000/pretrained_model
5
+ AIC_ACT_STAGED_PROGRESS_EPS_M=0.0015
6
+ AIC_ACT_DEVICE=cpu
7
+ AIC_ACT_POLICY_PATH_DEFAULT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
8
+ AIC_ACT_POLICY_PATH_GUARDED_INSERT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_guarded_insert/2026-05-06_00-46-05/checkpoints/010000/pretrained_model
9
+ AIC_ACT_STAGED_ENABLE_STAGED_WRAPPER=true
10
+ AIC_ACT_STAGED_RETRY_COUNT=3
results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/policy_env.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ AIC_ACT_STAGED_MAX_GUARDED_INSERT_SEC=5
2
+ AIC_ACT_POLICY_PATH_APPROACH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
3
+ AIC_ACT_POLICY_PATH_RETRY_OR_FINISH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_retry_or_finish/2026-05-06_00-51-10/checkpoints/010000/pretrained_model
4
+ AIC_ACT_POLICY_PATH_ALIGN=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_align/2026-05-06_00-41-13/checkpoints/010000/pretrained_model
5
+ AIC_ACT_STAGED_PROGRESS_EPS_M=0.0015
6
+ AIC_SCRIPTED_INSERT_STIFFNESS=400,400,400,85,85,85
7
+ AIC_ACT_DEVICE=cpu
8
+ AIC_ACT_POLICY_PATH_DEFAULT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
9
+ AIC_ACT_POLICY_PATH_GUARDED_INSERT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_guarded_insert/2026-05-06_00-46-05/checkpoints/010000/pretrained_model
10
+ AIC_ACT_STAGED_ENABLE_STAGED_WRAPPER=true
11
+ AIC_ACT_STAGED_RETRY_COUNT=3
12
+ SCRIPTED_ENV=AIC_SCRIPTED_INSERT_STIFFNESS=400,400,400,85,85,85
results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/bag_trial_1_20261027_012629_993/bag_trial_1_20261027_012629_993_0.mcap ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ad2ca35e0a21ea888f7a14acb9b8e4f65ce2adccf2d0943cacf1a28ced0cc09
3
+ size 59934799
results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/bag_trial_1_20261027_012629_993/metadata.yaml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ rosbag2_bagfile_information:
2
+ version: 9
3
+ storage_identifier: mcap
4
+ duration:
5
+ nanoseconds: 25537181114
6
+ starting_time:
7
+ nanoseconds_since_epoch: 1793064389995279549
8
+ message_count: 51977
9
+ topics_with_message_count:
10
+ - topic_metadata:
11
+ name: /aic_controller/pose_commands
12
+ type: aic_control_interfaces/msg/MotionUpdate
13
+ serialization_format: cdr
14
+ offered_qos_profiles:
15
+ []
16
+ type_description_hash: ""
17
+ message_count: 338
18
+ - topic_metadata:
19
+ name: /scoring/tf
20
+ type: tf2_msgs/msg/TFMessage
21
+ serialization_format: cdr
22
+ offered_qos_profiles:
23
+ []
24
+ type_description_hash: ""
25
+ message_count: 12579
26
+ - topic_metadata:
27
+ name: /fts_broadcaster/wrench
28
+ type: geometry_msgs/msg/WrenchStamped
29
+ serialization_format: cdr
30
+ offered_qos_profiles:
31
+ []
32
+ type_description_hash: ""
33
+ message_count: 1257
34
+ - topic_metadata:
35
+ name: /aic_controller/controller_state
36
+ type: aic_control_interfaces/msg/ControllerState
37
+ serialization_format: cdr
38
+ offered_qos_profiles:
39
+ []
40
+ type_description_hash: ""
41
+ message_count: 12600
42
+ - topic_metadata:
43
+ name: /tf
44
+ type: tf2_msgs/msg/TFMessage
45
+ serialization_format: cdr
46
+ offered_qos_profiles:
47
+ []
48
+ type_description_hash: ""
49
+ message_count: 12601
50
+ - topic_metadata:
51
+ name: /joint_states
52
+ type: sensor_msgs/msg/JointState
53
+ serialization_format: cdr
54
+ offered_qos_profiles:
55
+ []
56
+ type_description_hash: ""
57
+ message_count: 12601
58
+ - topic_metadata:
59
+ name: /tf_static
60
+ type: tf2_msgs/msg/TFMessage
61
+ serialization_format: cdr
62
+ offered_qos_profiles:
63
+ []
64
+ type_description_hash: ""
65
+ message_count: 1
66
+ compression_format: ""
67
+ compression_mode: ""
68
+ relative_file_paths:
69
+ - bag_trial_1_20261027_012629_993_0.mcap
70
+ files:
71
+ - path: bag_trial_1_20261027_012629_993_0.mcap
72
+ starting_time:
73
+ nanoseconds_since_epoch: 1793064389995279549
74
+ duration:
75
+ nanoseconds: 25537181114
76
+ message_count: 51977
77
+ custom_data: ~
78
+ ros_distro: kilted
results/runs/stitch-a0-base-t1-004-gtoff-20261027_012616/results/scoring.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ total: 60.015849327888439
2
+ trial_1:
3
+ tier_1:
4
+ score: 1
5
+ message: Model validation succeeded.
6
+ tier_2:
7
+ score: 19.345562038599418
8
+ message: Scoring succeeded.
9
+ categories:
10
+ contacts:
11
+ score: 0
12
+ message: No contact detected.
13
+ duration:
14
+ score: 7.6359272727272742
15
+ message: "Task duration: 25.00 seconds."
16
+ insertion force:
17
+ score: 0
18
+ message: No excessive force detected
19
+ trajectory efficiency:
20
+ score: 6
21
+ message: "Total end-effector path length: 0.00 m, initial plug-port distance: 0.33 m"
22
+ trajectory smoothness:
23
+ score: 5.709634765872142
24
+ message: "Average linear jerk magnitude of the end effector: 2.42 m/s^3"
25
+ tier_3:
26
+ score: 39.670287289289021
27
+ message: Partial insertion detected with distance of 0.01m.
results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/policy_env.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ AIC_ACT_STAGED_MAX_GUARDED_INSERT_SEC=5
2
+ AIC_ACT_POLICY_PATH_APPROACH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
3
+ AIC_ACT_POLICY_PATH_RETRY_OR_FINISH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_retry_or_finish/2026-05-06_00-51-10/checkpoints/010000/pretrained_model
4
+ AIC_ACT_POLICY_PATH_ALIGN=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_align/2026-05-06_00-41-13/checkpoints/010000/pretrained_model
5
+ AIC_ACT_STAGED_PROGRESS_EPS_M=0.0015
6
+ AIC_SCRIPTED_INSERT_STIFFNESS=400,400,400,85,85,85
7
+ AIC_ACT_DEVICE=cpu
8
+ AIC_ACT_POLICY_PATH_DEFAULT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
9
+ AIC_ACT_POLICY_PATH_GUARDED_INSERT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_guarded_insert/2026-05-06_00-46-05/checkpoints/010000/pretrained_model
10
+ AIC_ACT_STAGED_ENABLE_STAGED_WRAPPER=true
11
+ AIC_ACT_STAGED_RETRY_COUNT=3
12
+ SCRIPTED_ENV=AIC_SCRIPTED_INSERT_STIFFNESS=400,400,400,85,85,85
results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/bag_trial_1_20261027_012730_159/bag_trial_1_20261027_012730_159_0.mcap ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c44c1fb872a494ddb2abb2270c8e0758d6bfc9116614591aa59ae5d538526f47
3
+ size 60057672
results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/bag_trial_1_20261027_012730_159/metadata.yaml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ rosbag2_bagfile_information:
2
+ version: 9
3
+ storage_identifier: mcap
4
+ duration:
5
+ nanoseconds: 25451578879
6
+ starting_time:
7
+ nanoseconds_since_epoch: 1793064450161510194
8
+ message_count: 52145
9
+ topics_with_message_count:
10
+ - topic_metadata:
11
+ name: /aic_controller/pose_commands
12
+ type: aic_control_interfaces/msg/MotionUpdate
13
+ serialization_format: cdr
14
+ offered_qos_profiles:
15
+ []
16
+ type_description_hash: ""
17
+ message_count: 338
18
+ - topic_metadata:
19
+ name: /scoring/tf
20
+ type: tf2_msgs/msg/TFMessage
21
+ serialization_format: cdr
22
+ offered_qos_profiles:
23
+ []
24
+ type_description_hash: ""
25
+ message_count: 12589
26
+ - topic_metadata:
27
+ name: /fts_broadcaster/wrench
28
+ type: geometry_msgs/msg/WrenchStamped
29
+ serialization_format: cdr
30
+ offered_qos_profiles:
31
+ []
32
+ type_description_hash: ""
33
+ message_count: 1260
34
+ - topic_metadata:
35
+ name: /aic_controller/controller_state
36
+ type: aic_control_interfaces/msg/ControllerState
37
+ serialization_format: cdr
38
+ offered_qos_profiles:
39
+ []
40
+ type_description_hash: ""
41
+ message_count: 12651
42
+ - topic_metadata:
43
+ name: /tf_static
44
+ type: tf2_msgs/msg/TFMessage
45
+ serialization_format: cdr
46
+ offered_qos_profiles:
47
+ []
48
+ type_description_hash: ""
49
+ message_count: 1
50
+ - topic_metadata:
51
+ name: /tf
52
+ type: tf2_msgs/msg/TFMessage
53
+ serialization_format: cdr
54
+ offered_qos_profiles:
55
+ []
56
+ type_description_hash: ""
57
+ message_count: 12653
58
+ - topic_metadata:
59
+ name: /joint_states
60
+ type: sensor_msgs/msg/JointState
61
+ serialization_format: cdr
62
+ offered_qos_profiles:
63
+ []
64
+ type_description_hash: ""
65
+ message_count: 12653
66
+ compression_format: ""
67
+ compression_mode: ""
68
+ relative_file_paths:
69
+ - bag_trial_1_20261027_012730_159_0.mcap
70
+ files:
71
+ - path: bag_trial_1_20261027_012730_159_0.mcap
72
+ starting_time:
73
+ nanoseconds_since_epoch: 1793064450161510194
74
+ duration:
75
+ nanoseconds: 25451578879
76
+ message_count: 52145
77
+ custom_data: ~
78
+ ros_distro: kilted
results/runs/stitch-a0-base-t2-004-gtoff-20261027_012716/results/scoring.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ total: 60.03165168757117
2
+ trial_1:
3
+ tier_1:
4
+ score: 1
5
+ message: Model validation succeeded.
6
+ tier_2:
7
+ score: 19.361735794591191
8
+ message: Scoring succeeded.
9
+ categories:
10
+ contacts:
11
+ score: 0
12
+ message: No contact detected.
13
+ duration:
14
+ score: 7.6350545454545449
15
+ message: "Task duration: 25.01 seconds."
16
+ insertion force:
17
+ score: 0
18
+ message: No excessive force detected
19
+ trajectory efficiency:
20
+ score: 6
21
+ message: "Total end-effector path length: 0.00 m, initial plug-port distance: 0.33 m"
22
+ trajectory smoothness:
23
+ score: 5.7266812491366483
24
+ message: "Average linear jerk magnitude of the end effector: 2.28 m/s^3"
25
+ tier_3:
26
+ score: 39.669915892979979
27
+ message: Partial insertion detected with distance of 0.01m.
results/runs/stitch-a0-base-t3-004-gtoff-20261027_012816/policy_env.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ AIC_ACT_STAGED_MAX_GUARDED_INSERT_SEC=5
2
+ AIC_ACT_POLICY_PATH_APPROACH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
3
+ AIC_ACT_POLICY_PATH_RETRY_OR_FINISH=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_retry_or_finish/2026-05-06_00-51-10/checkpoints/010000/pretrained_model
4
+ AIC_ACT_POLICY_PATH_ALIGN=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_align/2026-05-06_00-41-13/checkpoints/010000/pretrained_model
5
+ AIC_ACT_STAGED_PROGRESS_EPS_M=0.0015
6
+ AIC_SCRIPTED_INSERT_STIFFNESS=400,400,400,85,85,85
7
+ AIC_ACT_DEVICE=cpu
8
+ AIC_ACT_POLICY_PATH_DEFAULT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_approach/2026-05-06_00-36-06/checkpoints/010000/pretrained_model
9
+ AIC_ACT_POLICY_PATH_GUARDED_INSERT=/mnt/sienarune/Black-Projects/Project-Automaton/Santa_Maria/code/aic-quantarune-isaac-training/quantarune_training/outputs/sc_stage_fixed_scene_curated_001_v1_guarded_insert/2026-05-06_00-46-05/checkpoints/010000/pretrained_model
10
+ AIC_ACT_STAGED_ENABLE_STAGED_WRAPPER=true
11
+ AIC_ACT_STAGED_RETRY_COUNT=3
12
+ SCRIPTED_ENV=AIC_SCRIPTED_INSERT_STIFFNESS=400,400,400,85,85,85