HanningHanning commited on
Commit
b14abf6
·
verified ·
1 Parent(s): d598531

Add DOMINO online-follow adjust_bottle dataset v1

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: DOMINO Online-Follow Adjust Bottle
3
+ language:
4
+ - en
5
+ license: apache-2.0
6
+ task_categories:
7
+ - robotics
8
+ tags:
9
+ - robotics
10
+ - embodied-ai
11
+ - dynamic-manipulation
12
+ - vision-language-action
13
+ - robot-manipulation
14
+ - domino
15
+ - aloha
16
+ - video
17
+ ---
18
+
19
+ # DOMINO Online-Follow: Adjust Bottle
20
+
21
+ This dataset contains **50** successful `adjust_bottle` demonstrations for the
22
+ ALOHA-AgileX embodiment in the DOMINO simulator. Unlike the original
23
+ precomputed-interception expert, the bottle first moves independently from outside
24
+ the camera view and the expert repeatedly observes, approaches, follows, grasps,
25
+ lifts, and completes the original upright placement task. The controller does not
26
+ receive a future object trajectory or a precomputed interception point.
27
+
28
+ ## Data summary
29
+
30
+ - Episodes: **50** (25 left-arm, 25 right-arm)
31
+ - Object assets: model 13 (**25**) and model 16 (**25**)
32
+ - Recorded control frames: **16,651**
33
+ - Cameras: `cam_high`, `cam_left_wrist`, `cam_right_wrist`
34
+ - Camera frames fully decoded during audit: **66,604**
35
+ - Nominal training FPS: **15**
36
+ - Object speed: 0.040--0.117 m/s
37
+ (mean 0.0964, median 0.1010)
38
+ - Entry angle: -7.4--7.4 degrees
39
+ - Unique scene seeds: **30**
40
+ - Unique scene-motion combinations: **50**
41
+ - Mean demonstration duration: 10.61 seconds
42
+
43
+ All 50 HDF5 episodes, instructions, trace files, and videos passed the repository
44
+ quality checker. All camera frames and videos were fully decoded; timestamps are
45
+ strictly increasing; the inactive arm remains fixed; and no wrong-arm language
46
+ labels were found. Full per-episode provenance and the acceptance audit are in
47
+ `summary.json` inside the archive.
48
+
49
+ ## Repository structure
50
+
51
+ ```text
52
+ dataset/
53
+ adjust_bottle/
54
+ aloha-agilex_clean_follow_fast_50.zip
55
+ provenance/
56
+ collect_data_dynamic_follow.py
57
+ demo_dynamicvla_follow_dataset.yml
58
+ adjust_bottle.py
59
+ adjust_bottle_instructions.json
60
+ manifest.json
61
+ LICENSE
62
+ ```
63
+
64
+ The ZIP follows the public DOMINO naming/layout convention and expands to:
65
+
66
+ ```text
67
+ aloha-agilex_clean_follow_fast/
68
+ data/ # episode0.hdf5 ... episode49.hdf5
69
+ instructions/ # 100 seen + 100 unseen language variants per episode
70
+ metrics/ # causal object/robot traces and quality measurements
71
+ video/ # one preview video per episode
72
+ scene_info.json
73
+ seed.txt
74
+ summary.json
75
+ ```
76
+
77
+ Archive size: **0.56 GiB**
78
+ SHA-256: `bffbe20ba8be9e34b81a4e6c11d2435e6640b17918b85a23346f4568460104fe`
79
+
80
+ ## Download
81
+
82
+ ```bash
83
+ hf download REPO_ID dataset/adjust_bottle/aloha-agilex_clean_follow_fast_50.zip --repo-type dataset --local-dir DOMINO-Online-Follow
84
+
85
+ unzip DOMINO-Online-Follow/dataset/adjust_bottle/aloha-agilex_clean_follow_fast_50.zip -d data/adjust_bottle/
86
+ ```
87
+
88
+ Replace `REPO_ID` with the dataset repository shown at the top of this page.
89
+
90
+ ## Training formats
91
+
92
+ The archive is the canonical DOMINO HDF5 release. It was also validated after
93
+ conversion to LeRobot v2.1 (16,601 usable PUMA frames at
94
+ 15 FPS). Derived LeRobot files and optical-flow/object-grounding
95
+ caches are intentionally excluded to avoid duplicating images and publishing
96
+ machine-specific runtime caches. The conversion scripts are provided by PUMA in
97
+ the DOMINO repository.
98
+
99
+ ## License and attribution
100
+
101
+ Released under Apache-2.0, following the upstream DOMINO repository and dataset.
102
+ If you use this data, cite the DOMINO paper and comply with the licenses of the
103
+ DOMINO simulator and its underlying robot/object assets.
104
+
105
+ ```bibtex
106
+ @article{fang2026towards,
107
+ title={Towards Generalizable Robotic Manipulation in Dynamic Environments},
108
+ author={Fang, Heng and Li, Shangru and Wang, Shuhan and Xi, Xuanyang and Liang, Dingkang and Bai, Xiang},
109
+ journal={arXiv preprint arXiv:2603.15620},
110
+ year={2026}
111
+ }
112
+ ```
dataset/adjust_bottle/aloha-agilex_clean_follow_fast_50.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bffbe20ba8be9e34b81a4e6c11d2435e6640b17918b85a23346f4568460104fe
3
+ size 603007635
manifest.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "dataset_name": "DOMINO Online-Follow Adjust Bottle",
4
+ "format": "DOMINO HDF5 archive",
5
+ "task": "adjust_bottle",
6
+ "embodiment": "aloha-agilex",
7
+ "condition": "clean",
8
+ "variant": "follow_fast",
9
+ "episodes": 50,
10
+ "source_bytes": 1047858870,
11
+ "episode_group_counts": {
12
+ "data": 50,
13
+ "instructions": 50,
14
+ "metrics": 50,
15
+ "video": 50
16
+ },
17
+ "artifact": {
18
+ "path": "dataset/adjust_bottle/aloha-agilex_clean_follow_fast_50.zip",
19
+ "size_bytes": 603007635,
20
+ "sha256": "bffbe20ba8be9e34b81a4e6c11d2435e6640b17918b85a23346f4568460104fe",
21
+ "file_count": 203,
22
+ "internal_root": "aloha-agilex_clean_follow_fast"
23
+ },
24
+ "provenance_files": {
25
+ "provenance/collect_data_dynamic_follow.py": {
26
+ "size_bytes": 66930,
27
+ "sha256": "4a501aeac4ab2643d360fd1ef1815656e969ef9e38049466ec0ac510d52add40"
28
+ },
29
+ "provenance/demo_dynamicvla_follow_dataset.yml": {
30
+ "size_bytes": 5139,
31
+ "sha256": "70a5f92d88006b27bdc6578df5fd21f6c4dc5a341eb595f1f09b2effc5a7750d"
32
+ },
33
+ "provenance/adjust_bottle.py": {
34
+ "size_bytes": 8544,
35
+ "sha256": "bd122764af3f2f3e8b236280983e8949506c5e96b4b9040529812d61ee48f115"
36
+ },
37
+ "provenance/adjust_bottle_instructions.json": {
38
+ "size_bytes": 2890,
39
+ "sha256": "3168108cde17a45c0671bda463a46559c4a3e1b0f914324a28c2999b505cf7eb"
40
+ }
41
+ },
42
+ "source_summary_sha256": "7cb74255a3380c5346b548c544a2d89013ec98c5683b3b9d0eef12e7195ceede",
43
+ "source_finalized_at_utc": "2026-07-28T15:28:44.229534+00:00",
44
+ "quality_audit": {
45
+ "audited_at_utc": "2026-07-28T15:39:36.607029+00:00",
46
+ "repository_checker_clean_episodes": 50,
47
+ "hdf5_episodes_opened": 50,
48
+ "hdf5_frames": 16651,
49
+ "camera_frames_fully_decoded": 66604,
50
+ "inactive_arm_max_delta_rad": 0.0,
51
+ "native_timestamps_strictly_increasing": true,
52
+ "trace_timestamps_match_recorded_timestep": true,
53
+ "mp4_metadata_validated": 50,
54
+ "mp4_videos_fully_decoded": 50,
55
+ "visual_contact_sheet_reviewed": true,
56
+ "instruction_files_validated": 50,
57
+ "language_variants_seen_per_episode": 100,
58
+ "language_variants_unseen_per_episode": 100,
59
+ "wrong_arm_language_labels": 0,
60
+ "issues": []
61
+ },
62
+ "repository": {
63
+ "commit": "1c215da781d38cd7defe9aac7a0c9eee661e8726",
64
+ "dirty": true,
65
+ "tracked_changes": [
66
+ "M description/task_instruction/adjust_bottle.json",
67
+ " M envs/adjust_bottle.py",
68
+ " M policy/PUMA/PUMA/dataloader/gr00t_lerobot/mixtures.py",
69
+ "MM script/collect_data_dynamic_follow.py",
70
+ " M task_config/demo_dynamicvla_follow_dataset.yml",
71
+ "?? script/publish_dynamic_follow_dataset.py"
72
+ ],
73
+ "origin": "https://github.com/H-EmbodVis/DOMINO.git"
74
+ },
75
+ "excluded_derived_data": [
76
+ "ALOHA conversion copy",
77
+ "LeRobot conversion copy",
78
+ "history optical-flow cache",
79
+ "object-grounding cache"
80
+ ]
81
+ }
provenance/adjust_bottle.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._base_task import Base_Task
2
+ from .utils import *
3
+ import sapien
4
+ import math
5
+ import numpy as np
6
+
7
+
8
+ class adjust_bottle(Base_Task):
9
+
10
+ def setup_demo(self, **kwags):
11
+ self._forced_qpose_tag = kwags.get("forced_qpose_tag")
12
+ self._forced_model_id = kwags.get("forced_model_id")
13
+ super()._init_task_env_(**kwags)
14
+
15
+ def load_actors(self):
16
+
17
+ self.qpose_tag = np.random.randint(0, 2)
18
+ qposes = [[0.707, 0.0, 0.0, -0.707], [0.707, 0.0, 0.0, 0.707]]
19
+ xlims = [[-0.12, -0.08], [0.08, 0.12]]
20
+
21
+ self.model_id = np.random.choice([13, 16])
22
+ # Optional dataset-balancing controls. Draw the normal random values
23
+ # first so the remaining scene RNG stream is unchanged; default task
24
+ # behavior therefore stays byte-for-byte compatible.
25
+ if self._forced_qpose_tag is not None:
26
+ forced_qpose_tag = int(self._forced_qpose_tag)
27
+ if forced_qpose_tag not in (0, 1):
28
+ raise ValueError("forced_qpose_tag must be 0 (left) or 1 (right)")
29
+ self.qpose_tag = forced_qpose_tag
30
+ if self._forced_model_id is not None:
31
+ forced_model_id = int(self._forced_model_id)
32
+ if forced_model_id not in (13, 16):
33
+ raise ValueError("forced_model_id must be 13 or 16")
34
+ self.model_id = forced_model_id
35
+
36
+ self.bottle = rand_create_actor(
37
+ self,
38
+ xlim=xlims[self.qpose_tag],
39
+ ylim=[-0.13, -0.08],
40
+ zlim=[0.752],
41
+ rotate_rand=True,
42
+ qpos=qposes[self.qpose_tag],
43
+ modelname="001_bottle",
44
+ convex=True,
45
+ rotate_lim=(0, 0, 0.4),
46
+ model_id=self.model_id,
47
+ )
48
+
49
+ if self.use_dynamic:
50
+ self.bottle.set_mass(0.01)
51
+ for component in self.bottle.actor.get_components():
52
+ if isinstance(component, sapien.physx.PhysxRigidDynamicComponent):
53
+ component.set_linear_damping(10.0)
54
+ component.set_angular_damping(10.0)
55
+
56
+ self.delay(4)
57
+ self.add_prohibit_area(self.bottle, padding=0.15)
58
+ self.left_target_pose = [-0.25, -0.12, 0.95, 0, 1, 0, 0]
59
+ self.right_target_pose = [0.25, -0.12, 0.95, 0, 1, 0, 0]
60
+
61
+ def play_once(self):
62
+ if self.use_dynamic:
63
+ return self._play_once_dynamic()
64
+ else:
65
+ return self._play_once_static()
66
+
67
+ def _play_once_static(self):
68
+ arm_tag = ArmTag("right" if self.qpose_tag == 1 else "left")
69
+ target_pose = (self.right_target_pose if self.qpose_tag == 1 else self.left_target_pose)
70
+
71
+ # Grasp -> Lift
72
+ self.move(self.grasp_actor(self.bottle, arm_tag=arm_tag, pre_grasp_dis=0.1))
73
+ self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.1, move_axis="arm"))
74
+
75
+ # Place
76
+ self.move(
77
+ self.place_actor(
78
+ self.bottle,
79
+ target_pose=target_pose,
80
+ arm_tag=arm_tag,
81
+ functional_point_id=0,
82
+ pre_dis=0.0,
83
+ is_open=False,
84
+ ))
85
+
86
+ self.info["info"] = {
87
+ "{A}": f"001_bottle/base{self.model_id}",
88
+ "{a}": str(arm_tag),
89
+ }
90
+ return self.info
91
+
92
+ def _play_once_dynamic(self):
93
+ arm_tag = ArmTag("right" if self.qpose_tag == 1 else "left")
94
+ target_pose = (self.right_target_pose if self.qpose_tag == 1 else self.left_target_pose)
95
+
96
+ current_bottle_pose = self.bottle.get_pose()
97
+ end_position = np.array([current_bottle_pose.p[0], current_bottle_pose.p[1], current_bottle_pose.p[2]])
98
+
99
+ self._intercept_position = end_position.copy()
100
+
101
+ def robot_action_sequence_sync(need_plan_mode):
102
+ grasp_result = self.grasp_actor(self.bottle, arm_tag=arm_tag, pre_grasp_dis=0.1)
103
+ if not grasp_result or grasp_result[1] is None or len(grasp_result[1]) == 0:
104
+ return
105
+ self.move(grasp_result)
106
+
107
+ table_bounds = (-0.35, 0.35, -0.25, 0.15)
108
+ success, start_pos = self.execute_dynamic_workflow(
109
+ target_actor=self.bottle,
110
+ end_position=end_position,
111
+ robot_action_sequence=robot_action_sequence_sync,
112
+ table_bounds=table_bounds,
113
+ )
114
+
115
+ if not success:
116
+ raise RuntimeError("Failed to generate dynamic trajectory")
117
+
118
+ for component in self.bottle.actor.get_components():
119
+ if isinstance(component, sapien.physx.PhysxRigidDynamicComponent):
120
+ try:
121
+ component.set_linear_velocity(np.zeros(3))
122
+ component.set_angular_velocity(np.zeros(3))
123
+ component.set_linear_damping(10.0)
124
+ component.set_angular_damping(10.0)
125
+ except Exception:
126
+ pass
127
+
128
+ self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.1, move_axis="arm"))
129
+
130
+ self.move(
131
+ self.place_actor(
132
+ self.bottle,
133
+ target_pose=target_pose,
134
+ arm_tag=arm_tag,
135
+ functional_point_id=0,
136
+ pre_dis=0.0,
137
+ is_open=False,
138
+ ))
139
+
140
+ self.info["info"] = {
141
+ "{A}": f"001_bottle/base{self.model_id}",
142
+ "{a}": str(arm_tag),
143
+ }
144
+ return self.info
145
+
146
+ def get_dynamic_motion_config(self) -> dict:
147
+ if not self.use_dynamic:
148
+ return None
149
+ current_bottle_pose = self.bottle.get_pose()
150
+ end_position = np.array([current_bottle_pose.p[0], current_bottle_pose.p[1], current_bottle_pose.p[2]])
151
+
152
+ return {
153
+ 'target_actor': self.bottle,
154
+ 'end_position': end_position,
155
+ 'table_bounds': (-0.35, 0.35, -0.15, 0.25),
156
+ }
157
+
158
+ def check_success(self):
159
+ target_hight = 0.9
160
+ bottle_pose = self.bottle.get_functional_point(0)
161
+ basic_check= ((self.qpose_tag == 0 and bottle_pose[0] < -0.15) or
162
+ (self.qpose_tag == 1 and bottle_pose[0] > 0.15)) and bottle_pose[2] > target_hight
163
+ if (not self.use_dynamic) or getattr(self, 'eval_mode', False):
164
+ return basic_check
165
+
166
+ intercept_pos = getattr(self, '_intercept_position', None)
167
+ if intercept_pos is None:
168
+ return basic_check
169
+
170
+ current_center = self.bottle.get_pose().p
171
+ displacement = np.linalg.norm(current_center - intercept_pos)
172
+ displacement_threshold = 0.1
173
+ displacement_check = displacement > displacement_threshold
174
+
175
+ left_ee_pose = self.robot.get_left_ee_pose()
176
+ right_ee_pose = self.robot.get_right_ee_pose()
177
+ left_ee_pos = np.array(left_ee_pose[:3])
178
+ right_ee_pos = np.array(right_ee_pose[:3])
179
+
180
+ dist_to_left = np.linalg.norm(current_center[:2] - left_ee_pos[:2])
181
+ dist_to_right = np.linalg.norm(current_center[:2] - right_ee_pos[:2])
182
+ proximity_threshold = 0.15
183
+ proximity_check = (dist_to_left < proximity_threshold) or (dist_to_right < proximity_threshold)
184
+
185
+ return basic_check and displacement_check and proximity_check
186
+
187
+ def check_stable(self):
188
+ if not self.use_dynamic:
189
+ return super().check_stable()
190
+
191
+ from .utils import cal_quat_dis
192
+ actors_list, actors_pose_list = [], []
193
+ dynamic_name = self.bottle.get_name()
194
+
195
+ for actor in self.scene.get_all_actors():
196
+ if actor.get_name() != dynamic_name:
197
+ actors_list.append(actor)
198
+
199
+ def get_sim(p1, p2):
200
+ return np.abs(cal_quat_dis(p1.q, p2.q) * 180)
201
+
202
+ is_stable, unstable_list = True, []
203
+
204
+ def check(times):
205
+ nonlocal is_stable
206
+ for _ in range(times):
207
+ self._update_kinematic_tasks()
208
+ self.scene.step()
209
+ for idx, actor in enumerate(actors_list):
210
+ actors_pose_list[idx].append(actor.get_pose())
211
+
212
+ for idx, actor in enumerate(actors_list):
213
+ final_pose = actors_pose_list[idx][-1]
214
+ for pose in actors_pose_list[idx][-200:]:
215
+ if get_sim(final_pose, pose) > 3.0:
216
+ is_stable = False
217
+ unstable_list.append(actor.get_name())
218
+ break
219
+
220
+ for _ in range(2000):
221
+ self._update_kinematic_tasks()
222
+ self.scene.step()
223
+ for actor in actors_list:
224
+ actors_pose_list.append([actor.get_pose()])
225
+ check(500)
226
+ return is_stable, unstable_list
provenance/adjust_bottle_instructions.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "full_description": "Pick up the bottle on the table headup with the correct arm",
3
+ "schema": "{A} notifies the bottle, {a} notifies the arm to manipulate the bottle",
4
+ "preference": "num of words should not exceed 15",
5
+ "seen": [
6
+ "Lift {A} head-up from the table.",
7
+ "Pick {A} up with {a} ensuring it stays head-up.",
8
+ "Grab {A} from the table and hold it head-up.",
9
+ "Utilize {a} to lift {A} while keeping it head-up.",
10
+ "Lift {A} ensuring it remains upright.",
11
+ "Grab {A} head-up using {a} from the table.",
12
+ "Hold {A} head-up after lifting it.",
13
+ "Use {a} to pick {A} up and keep it head-up.",
14
+ "Pick {A} head-up and hold it steady.",
15
+ "Use {a} to grab and lift {A} head-up.",
16
+ "Grab {A} from the table with {a}",
17
+ "Lift the bottle {A} headup from the table",
18
+ "Raise {A} in a head-up position",
19
+ "Use {a} to lift {A} head-up",
20
+ "Position {A} head-up and lift it",
21
+ "Grab {A} with {a} in a head-up way",
22
+ "Lift the bottle {A} up from the table",
23
+ "Pick {A} head-up using {a}",
24
+ "Grab {A} and lift it into a head-up position",
25
+ "Use {a} to pick up {A} in the correct orientation",
26
+ "Lift {A} from the table upright",
27
+ "Use {a} to hold {A} from the table",
28
+ "Identify {A} and grab it with {a}",
29
+ "Pick {A} upright from the table",
30
+ "Lift {A} using {a} and hold upright",
31
+ "Take {A} from the table and keep upright",
32
+ "Grab {A} and lift it with {a}",
33
+ "Pick up {A} upright from the table",
34
+ "Hold {A} upright after lifting with {a}",
35
+ "Lift {A} from the table and secure upright",
36
+ "Lift {A} from the table with {a}",
37
+ "Pick {A} upright from the table",
38
+ "Grab {A} and lift it upright",
39
+ "Lift {A} head-up from the table",
40
+ "Using {a}, pick {A} upright",
41
+ "Secure {A} upright with {a}",
42
+ "Hold {A} upright from the table",
43
+ "Pick {A} and keep it upright",
44
+ "Lift {A} upright carefully using {a}",
45
+ "Carefully grab {A} head-up",
46
+ "Pick up {A} from the table carefully.",
47
+ "Use {a} to pick up {A} from the table.",
48
+ "Locate {A} and lift it upright with {a}.",
49
+ "Raise {A} from the table using the correct arm, {a}.",
50
+ "Grab {A} and lift it upward from the table.",
51
+ "Use the correct arm to pick up {A}.",
52
+ "Lift {A} off the table and hold it upright.",
53
+ "Pick up {A} from the table using {a}.",
54
+ "Lift {A} from the table without mentioning the arm.",
55
+ "Find {A} on the table and raise it using {a}."
56
+ ],
57
+ "unseen": [
58
+ "Pick up {A} from the table head-up.",
59
+ "Use {a} to grab {A} head-up.",
60
+ "Use {a} to grab the bottle {A}",
61
+ "Pick up {A} using the correct arm",
62
+ "Grab {A} from the table with {a}",
63
+ "Pick up {A} carefully using {a}",
64
+ "Pick up {A} using {a} in an upright position",
65
+ "Use {a} to grab {A} upright",
66
+ "Lift {A} from the table using {a}.",
67
+ "Grab {A} on the table and raise it."
68
+ ]
69
+ }
provenance/collect_data_dynamic_follow.py ADDED
@@ -0,0 +1,1659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collect DynamicVLA-style online-follow demonstrations in DOMINO.
3
+
4
+ This collector is deliberately separate from ``script/collect_data.py``. It
5
+ does not compute an interception point or pre-generate an object trajectory:
6
+
7
+ 1. the object receives one planar initial velocity and moves under PhysX;
8
+ 2. the robot observes only the current/past object poses and estimates velocity
9
+ with a finite difference;
10
+ 3. every short control horizon it replans to the updated approach/grasp pose;
11
+ 4. while closing, the object is released back to normal 6-DoF contact dynamics.
12
+
13
+ The object pose is privileged teacher information used only to create the
14
+ demonstration. A learned policy is expected to infer the same temporal signal
15
+ from images (for example with object-centric slots), not receive this pose at
16
+ deployment time.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import shutil
25
+ import sys
26
+ import time
27
+ from dataclasses import dataclass, replace
28
+ from pathlib import Path
29
+ from statistics import NormalDist
30
+ from typing import Any
31
+
32
+ import numpy as np
33
+ import sapien
34
+ import transforms3d as t3d
35
+ import yaml
36
+
37
+
38
+ REPO_ROOT = Path(__file__).resolve().parents[1]
39
+ if str(REPO_ROOT) not in sys.path:
40
+ sys.path.insert(0, str(REPO_ROOT))
41
+
42
+ from envs._GLOBAL_CONFIGS import CONFIGS_PATH # noqa: E402
43
+ from envs.adjust_bottle import adjust_bottle # noqa: E402
44
+ from envs.utils import ArmTag # noqa: E402
45
+
46
+
47
+ _FATAL_INFRASTRUCTURE_ERROR_MARKERS = (
48
+ "errorextensionnotpresent",
49
+ "failed to find a supported physical device",
50
+ "failed to find device",
51
+ "vulkan",
52
+ )
53
+
54
+
55
+ def is_fatal_infrastructure_error(error: BaseException) -> bool:
56
+ """Return whether retrying with another scene seed cannot fix ``error``."""
57
+
58
+ message = f"{type(error).__name__}: {error}".lower()
59
+ return any(marker in message for marker in _FATAL_INFRASTRUCTURE_ERROR_MARKERS)
60
+
61
+
62
+ @dataclass
63
+ class FollowSettings:
64
+ controller_mode: str = "plan_prefix"
65
+ speed_x: float = 0.025
66
+ speed_y: float = 0.010
67
+ offscreen_start_x: float = 0.0
68
+ object_only_seconds: float = 0.55
69
+ prediction_horizon_seconds: float = 0.23
70
+ replanning_horizon_steps: int = 40
71
+ medium_horizon_steps: int = 80
72
+ catchup_horizon_steps: int = 160
73
+ frame_stride_steps: int = 8
74
+ pre_grasp_distance: float = 0.10
75
+ approach_tolerance: float = 0.025
76
+ grasp_tolerance: float = 0.018
77
+ follow_hold_seconds: float = 0.35
78
+ close_seconds: float = 0.72
79
+ release_fraction: float = 0.58
80
+ lift_height: float = 0.14
81
+ settle_seconds: float = 0.30
82
+ max_approach_cycles: int = 28
83
+ max_descend_cycles: int = 18
84
+ velocity_ema: float = 0.65
85
+ servo_replan_steps: int = 50
86
+ servo_position_gain: float = 5.0
87
+ servo_max_joint_velocity: float = 1.4
88
+ servo_max_joint_acceleration: float = 3.0
89
+ servo_max_position_lead: float = 0.08
90
+ complete_original_task: bool = False
91
+ place_max_seconds: float = 3.0
92
+ place_position_tolerance: float = 0.015
93
+ place_control_position_tolerance: float = 0.015
94
+ place_orientation_tolerance_degrees: float = 12.0
95
+ upright_axis_tolerance_degrees: float = 12.0
96
+ place_max_joint_velocity: float = 0.8
97
+ place_max_joint_acceleration: float = 1.2
98
+ object_mass_kg: float | None = None
99
+ held_linear_damping: float = 0.2
100
+ held_angular_damping: float = 5.0
101
+ held_static_friction: float | None = None
102
+ held_dynamic_friction: float | None = None
103
+ grasp_settle_seconds: float = 0.0
104
+ stabilize_grasp_with_drive: bool = False
105
+ grasp_drive_stiffness: float = 1.0e5
106
+ grasp_drive_damping: float = 1.0e3
107
+ grasp_drive_force_limit: float = 1.0e6
108
+ grasp_drive_limit_epsilon: float = 1.0e-6
109
+
110
+ @classmethod
111
+ def from_dict(cls, values: dict[str, Any] | None) -> "FollowSettings":
112
+ if not values:
113
+ return cls()
114
+ valid = cls.__dataclass_fields__.keys()
115
+ unknown = sorted(set(values) - set(valid))
116
+ if unknown:
117
+ raise ValueError(f"Unknown dynamic_follow settings: {unknown}")
118
+ settings = cls(**values)
119
+ if settings.controller_mode not in {"plan_prefix", "smooth_joint_servo"}:
120
+ raise ValueError(
121
+ "controller_mode must be 'plan_prefix' or 'smooth_joint_servo'"
122
+ )
123
+ if settings.complete_original_task and settings.controller_mode != "smooth_joint_servo":
124
+ raise ValueError(
125
+ "complete_original_task currently requires smooth_joint_servo"
126
+ )
127
+ return settings
128
+
129
+
130
+ @dataclass
131
+ class FollowDistributionSettings:
132
+ """Deterministic low-discrepancy schedule for a dataset-sized run."""
133
+
134
+ enabled: bool = False
135
+ schedule_size: int = 50
136
+ speed_mean: float = 0.08
137
+ speed_sigma: float = 0.1 / 3.0
138
+ speed_min: float = 0.04
139
+ speed_max: float = 0.10
140
+ entry_angle_max_degrees: float = 8.0
141
+ offscreen_start_min: float = 0.56
142
+ offscreen_start_max: float = 0.60
143
+ action_start_abs_x_min: float = 0.44
144
+ action_start_abs_x_max: float = 0.47
145
+ follow_hold_min: float = 0.50
146
+ follow_hold_max: float = 0.70
147
+
148
+ @classmethod
149
+ def from_dict(
150
+ cls, values: dict[str, Any] | None
151
+ ) -> "FollowDistributionSettings":
152
+ if not values:
153
+ return cls()
154
+ valid = cls.__dataclass_fields__.keys()
155
+ unknown = sorted(set(values) - set(valid))
156
+ if unknown:
157
+ raise ValueError(
158
+ f"Unknown dynamic_follow_distribution settings: {unknown}"
159
+ )
160
+ settings = cls(**values)
161
+ if settings.schedule_size <= 0:
162
+ raise ValueError("distribution schedule_size must be positive")
163
+ if not 0 < settings.speed_min <= settings.speed_max:
164
+ raise ValueError("distribution speed range must be positive and ordered")
165
+ if settings.speed_sigma <= 0:
166
+ raise ValueError("distribution speed_sigma must be positive")
167
+ for low_name, high_name in (
168
+ ("offscreen_start_min", "offscreen_start_max"),
169
+ ("action_start_abs_x_min", "action_start_abs_x_max"),
170
+ ("follow_hold_min", "follow_hold_max"),
171
+ ):
172
+ if getattr(settings, low_name) > getattr(settings, high_name):
173
+ raise ValueError(f"{low_name} must not exceed {high_name}")
174
+ if settings.action_start_abs_x_max >= settings.offscreen_start_min:
175
+ raise ValueError(
176
+ "action-start x must remain inside the minimum offscreen x"
177
+ )
178
+ return settings
179
+
180
+
181
+ def van_der_corput(index: int, base: int) -> float:
182
+ """Return one element of a one-dimensional low-discrepancy sequence."""
183
+
184
+ value = 0.0
185
+ denominator = 1.0
186
+ while index > 0:
187
+ index, remainder = divmod(index, base)
188
+ denominator *= base
189
+ value += remainder / denominator
190
+ return value
191
+
192
+
193
+ def build_follow_schedule(
194
+ base: FollowSettings,
195
+ distribution: FollowDistributionSettings,
196
+ ) -> list[tuple[FollowSettings, dict[str, float]]]:
197
+ """Create a reproducible schedule whose prefixes already cover the range.
198
+
199
+ Speed uses the configured clipped normal distribution. The dataclass
200
+ defaults reproduce the old DOMINO sampler, while dataset configs may use a
201
+ harder profile. Other variables use different low-discrepancy bases to
202
+ avoid coupling.
203
+ """
204
+
205
+ if not distribution.enabled:
206
+ speed = float(np.hypot(base.speed_x, base.speed_y))
207
+ angle = float(np.degrees(np.arctan2(base.speed_y, base.speed_x)))
208
+ return [
209
+ (
210
+ base,
211
+ {
212
+ "target_speed_mps": speed,
213
+ "entry_angle_degrees": angle,
214
+ "offscreen_start_abs_x_m": base.offscreen_start_x,
215
+ "action_start_abs_x_m": (
216
+ base.offscreen_start_x
217
+ - base.object_only_seconds * abs(base.speed_x)
218
+ ),
219
+ "object_only_seconds": base.object_only_seconds,
220
+ "follow_hold_seconds": base.follow_hold_seconds,
221
+ },
222
+ )
223
+ ]
224
+
225
+ normal = NormalDist(distribution.speed_mean, distribution.speed_sigma)
226
+ schedule: list[tuple[FollowSettings, dict[str, float]]] = []
227
+ for episode in range(distribution.schedule_size):
228
+ # Base 2 gives useful prefix coverage: median, low, high, extreme-low.
229
+ speed_quantile = van_der_corput(episode + 1, 2)
230
+ raw_speed = abs(normal.inv_cdf(speed_quantile))
231
+ speed = float(
232
+ np.clip(raw_speed, distribution.speed_min, distribution.speed_max)
233
+ )
234
+
235
+ angle_unit = van_der_corput(episode + 1, 3)
236
+ angle_degrees = (
237
+ 2.0 * angle_unit - 1.0
238
+ ) * distribution.entry_angle_max_degrees
239
+ angle_radians = np.radians(angle_degrees)
240
+ speed_x = float(speed * np.cos(angle_radians))
241
+ speed_y = float(speed * np.sin(angle_radians))
242
+
243
+ offscreen_unit = van_der_corput(episode + 1, 5)
244
+ offscreen_start = float(
245
+ distribution.offscreen_start_min
246
+ + offscreen_unit
247
+ * (distribution.offscreen_start_max - distribution.offscreen_start_min)
248
+ )
249
+ action_start_unit = van_der_corput(episode + 1, 7)
250
+ action_start_abs_x = float(
251
+ distribution.action_start_abs_x_min
252
+ + action_start_unit
253
+ * (
254
+ distribution.action_start_abs_x_max
255
+ - distribution.action_start_abs_x_min
256
+ )
257
+ )
258
+ object_only_seconds = (
259
+ offscreen_start - action_start_abs_x
260
+ ) / max(speed_x, 1e-6)
261
+
262
+ hold_unit = van_der_corput(episode + 1, 11)
263
+ follow_hold = float(
264
+ distribution.follow_hold_min
265
+ + hold_unit
266
+ * (distribution.follow_hold_max - distribution.follow_hold_min)
267
+ )
268
+ episode_settings = replace(
269
+ base,
270
+ speed_x=speed_x,
271
+ speed_y=speed_y,
272
+ offscreen_start_x=offscreen_start,
273
+ object_only_seconds=object_only_seconds,
274
+ follow_hold_seconds=follow_hold,
275
+ )
276
+ schedule.append(
277
+ (
278
+ episode_settings,
279
+ {
280
+ "target_speed_mps": speed,
281
+ "entry_angle_degrees": float(angle_degrees),
282
+ "offscreen_start_abs_x_m": offscreen_start,
283
+ "action_start_abs_x_m": action_start_abs_x,
284
+ "object_only_seconds": float(object_only_seconds),
285
+ "follow_hold_seconds": follow_hold,
286
+ },
287
+ )
288
+ )
289
+ return schedule
290
+
291
+
292
+ class PoseVelocityObserver:
293
+ """Causal finite-difference velocity observer with light EMA smoothing."""
294
+
295
+ def __init__(self, dt: float, ema: float):
296
+ self.dt = float(dt)
297
+ self.ema = float(ema)
298
+ self.last_position: np.ndarray | None = None
299
+ self.last_step: int | None = None
300
+ self.velocity = np.zeros(3, dtype=np.float64)
301
+
302
+ def observe(self, position: np.ndarray, step: int) -> np.ndarray:
303
+ position = np.asarray(position, dtype=np.float64)
304
+ if self.last_position is not None and self.last_step is not None:
305
+ elapsed = max((step - self.last_step) * self.dt, self.dt)
306
+ measured = (position - self.last_position) / elapsed
307
+ self.velocity = self.ema * measured + (1.0 - self.ema) * self.velocity
308
+ self.last_position = position.copy()
309
+ self.last_step = int(step)
310
+ return self.velocity.copy()
311
+
312
+
313
+ class OnlineFollowEpisode:
314
+ """State-machine controller and recorder for one demonstration."""
315
+
316
+ def __init__(self, env: adjust_bottle, settings: FollowSettings):
317
+ self.env = env
318
+ self.settings = settings
319
+ self.dt = float(env.scene.get_timestep())
320
+ self.sim_step = 0
321
+ self.stage = "initial"
322
+ self.target_pose = np.full(7, np.nan, dtype=np.float64)
323
+ self.observer = PoseVelocityObserver(self.dt, settings.velocity_ema)
324
+ self.records: dict[str, list[Any]] = {
325
+ "sim_step": [],
326
+ "sim_time_seconds": [],
327
+ "stage": [],
328
+ "object_position": [],
329
+ "object_linear_velocity_physics": [],
330
+ "object_linear_velocity_estimate": [],
331
+ "ee_position": [],
332
+ "target_position": [],
333
+ "gripper": [],
334
+ "arm_joint_position": [],
335
+ "arm_joint_velocity_command": [],
336
+ }
337
+ self._original_shape_materials: list[tuple[Any, Any]] = []
338
+ self._held_shape_materials: list[tuple[Any, Any]] = []
339
+ self._held_friction_actor_names: set[str] = set()
340
+ self._object_component = env._get_rigid_dynamic_component(env.bottle)
341
+ if self._object_component is None:
342
+ raise RuntimeError("Bottle has no PhysX rigid-dynamic component")
343
+ if settings.object_mass_kg is not None:
344
+ env.bottle.set_mass(float(settings.object_mass_kg))
345
+ self._released = False
346
+ self._grasp_drive: Any | None = None
347
+ self._grasp_contact_links: list[str] = []
348
+ self._servo_position: np.ndarray | None = None
349
+ self._servo_velocity = np.zeros(6, dtype=np.float64)
350
+ self._last_capture_sim_step: int | None = None
351
+
352
+ @property
353
+ def arm(self) -> str:
354
+ return "right" if self.env.qpose_tag == 1 else "left"
355
+
356
+ def _ee_pose(self) -> np.ndarray:
357
+ pose = (self.env.robot.get_right_ee_pose() if self.arm == "right"
358
+ else self.env.robot.get_left_ee_pose())
359
+ return np.asarray(pose, dtype=np.float64)
360
+
361
+ def _gripper_value(self) -> float:
362
+ return float(self.env.robot.get_right_gripper_val() if self.arm == "right"
363
+ else self.env.robot.get_left_gripper_val())
364
+
365
+ def _object_position(self) -> np.ndarray:
366
+ return np.asarray(self.env.bottle.get_pose().p, dtype=np.float64)
367
+
368
+ def _arm_joint_position(self) -> np.ndarray:
369
+ values = (self.env.robot.get_right_arm_real_jointState()
370
+ if self.arm == "right"
371
+ else self.env.robot.get_left_arm_real_jointState())
372
+ return np.asarray(values[:-1], dtype=np.float64)
373
+
374
+ def _record(self) -> None:
375
+ object_position = self._object_position()
376
+ velocity_estimate = self.observer.velocity.copy()
377
+ try:
378
+ physics_velocity = np.asarray(
379
+ self._object_component.get_linear_velocity(), dtype=np.float64
380
+ )
381
+ except Exception:
382
+ physics_velocity = np.full(3, np.nan, dtype=np.float64)
383
+ self.records["sim_step"].append(self.sim_step)
384
+ self.records["sim_time_seconds"].append(self.sim_step * self.dt)
385
+ self.records["stage"].append(self.stage)
386
+ self.records["object_position"].append(object_position)
387
+ self.records["object_linear_velocity_physics"].append(physics_velocity)
388
+ self.records["object_linear_velocity_estimate"].append(velocity_estimate)
389
+ self.records["ee_position"].append(self._ee_pose()[:3])
390
+ self.records["target_position"].append(self.target_pose[:3].copy())
391
+ self.records["gripper"].append(self._gripper_value())
392
+ self.records["arm_joint_position"].append(self._arm_joint_position())
393
+ self.records["arm_joint_velocity_command"].append(
394
+ self._servo_velocity.copy()
395
+ )
396
+
397
+ def _capture(self) -> None:
398
+ # The final quality snapshot can coincide with the regular stride
399
+ # capture. Never serialize the same simulator state twice: duplicate
400
+ # terminal frames create non-increasing native timestamps and subtly
401
+ # overweight the terminal action during training.
402
+ if self._last_capture_sim_step == self.sim_step:
403
+ return
404
+ self.env._update_render()
405
+ self.env._take_picture()
406
+ self._last_capture_sim_step = self.sim_step
407
+
408
+ def step(self, gripper_value: float | None = None) -> None:
409
+ if gripper_value is not None:
410
+ # A large epsilon applies the requested value directly. The gripper
411
+ # drive itself remains force/contact controlled by PhysX.
412
+ self.env.robot.set_gripper(gripper_value, self.arm, gripper_eps=-1.0)
413
+ self.env._update_kinematic_tasks()
414
+ self.env.scene.step()
415
+ self.sim_step += 1
416
+ self._record()
417
+ if self.sim_step % self.settings.frame_stride_steps == 0:
418
+ self._capture()
419
+
420
+ def hold(self, steps: int, gripper_value: float | None = None) -> None:
421
+ for _ in range(max(0, int(steps))):
422
+ self.step(gripper_value=gripper_value)
423
+
424
+ def start_independent_motion(self, velocity: np.ndarray) -> None:
425
+ """Apply one physical velocity impulse on a frictionless planar surface."""
426
+
427
+ low_friction = self.env.scene.create_physical_material(0.0, 0.0, 0.0)
428
+ for actor in self.env.scene.get_all_actors():
429
+ if actor.get_name() not in {self.env.bottle.get_name(), "table"}:
430
+ continue
431
+ for component in actor.get_components():
432
+ if not hasattr(component, "get_collision_shapes"):
433
+ continue
434
+ for shape in component.get_collision_shapes():
435
+ self._original_shape_materials.append(
436
+ (shape, shape.get_physical_material())
437
+ )
438
+ shape.set_physical_material(low_friction)
439
+
440
+ component = self._object_component
441
+ component.set_linear_damping(0.0)
442
+ component.set_angular_damping(0.0)
443
+ # Planar moving-platform dynamics: x/y are free; z and rotation are held
444
+ # until the fingers surround the object. The pose is never teleported.
445
+ component.set_locked_motion_axes([False, False, True, True, True, True])
446
+ component.set_angular_velocity(np.zeros(3))
447
+ component.set_linear_velocity(np.asarray(velocity, dtype=np.float64))
448
+
449
+ def release_to_contact_dynamics(self) -> None:
450
+ if self._released:
451
+ return
452
+ for shape, material in self._original_shape_materials:
453
+ shape.set_physical_material(material)
454
+ self._original_shape_materials.clear()
455
+ if (
456
+ self.settings.held_static_friction is not None
457
+ and self.settings.held_dynamic_friction is not None
458
+ ):
459
+ held_material = self.env.scene.create_physical_material(
460
+ float(self.settings.held_static_friction),
461
+ float(self.settings.held_dynamic_friction),
462
+ 0.0,
463
+ )
464
+ seen_shapes: set[int] = set()
465
+
466
+ def apply_held_material(entity: Any) -> None:
467
+ components = (
468
+ entity.get_components()
469
+ if hasattr(entity, "get_components")
470
+ else [entity]
471
+ )
472
+ for component in components:
473
+ if not hasattr(component, "get_collision_shapes"):
474
+ continue
475
+ for shape in component.get_collision_shapes():
476
+ shape_id = id(shape)
477
+ if shape_id in seen_shapes:
478
+ continue
479
+ seen_shapes.add(shape_id)
480
+ self._held_shape_materials.append(
481
+ (shape, shape.get_physical_material())
482
+ )
483
+ shape.set_physical_material(held_material)
484
+ self._held_friction_actor_names.add(entity.get_name())
485
+
486
+ apply_held_material(self.env.bottle.actor)
487
+ active_gripper = (
488
+ self.env.robot.right_gripper
489
+ if self.arm == "right"
490
+ else self.env.robot.left_gripper
491
+ )
492
+ for joint_info in active_gripper:
493
+ apply_held_material(joint_info[0].child_link)
494
+ print(
495
+ "[dynamic-follow] held contact material: "
496
+ f"{len(self._held_shape_materials)} shapes on "
497
+ f"{sorted(self._held_friction_actor_names)}"
498
+ )
499
+ self._object_component.set_locked_motion_axes([False] * 6)
500
+ self._object_component.set_linear_damping(
501
+ self.settings.held_linear_damping
502
+ )
503
+ self._object_component.set_angular_damping(
504
+ self.settings.held_angular_damping
505
+ )
506
+ self._released = True
507
+
508
+ def restore_materials(self) -> None:
509
+ if self._grasp_drive is not None:
510
+ try:
511
+ self._grasp_drive.disable()
512
+ except Exception:
513
+ pass
514
+ self._grasp_drive = None
515
+ for shape, material in (
516
+ self._held_shape_materials + self._original_shape_materials
517
+ ):
518
+ try:
519
+ shape.set_physical_material(material)
520
+ except Exception:
521
+ pass
522
+ self._held_shape_materials.clear()
523
+ self._original_shape_materials.clear()
524
+
525
+ def attach_verified_grasp_drive(self) -> None:
526
+ """Stabilize an already physical, bilateral grasp without teleporting."""
527
+
528
+ active_gripper = (
529
+ self.env.robot.right_gripper
530
+ if self.arm == "right"
531
+ else self.env.robot.left_gripper
532
+ )
533
+ finger_links = [joint_info[0].child_link for joint_info in active_gripper]
534
+ finger_names = {link.get_name() for link in finger_links}
535
+ bottle_name = self.env.bottle.get_name()
536
+ contacting: set[str] = set()
537
+ for contact in self.env.scene.get_contacts():
538
+ name0 = contact.bodies[0].entity.name
539
+ name1 = contact.bodies[1].entity.name
540
+ if name0 == bottle_name and name1 in finger_names:
541
+ contacting.add(name1)
542
+ elif name1 == bottle_name and name0 in finger_names:
543
+ contacting.add(name0)
544
+ self._grasp_contact_links = sorted(contacting)
545
+ if contacting != finger_names:
546
+ raise RuntimeError(
547
+ "grasp stabilization requires bilateral finger contact: "
548
+ f"expected={sorted(finger_names)} actual={sorted(contacting)}"
549
+ )
550
+
551
+ ee_joint = (
552
+ self.env.robot.right_ee
553
+ if self.arm == "right"
554
+ else self.env.robot.left_ee
555
+ )
556
+ parent_link = ee_joint.child_link
557
+ parent_pose = parent_link.get_pose()
558
+ child_pose = self._object_component.get_pose()
559
+ pose_in_parent = parent_pose.inv() * child_pose
560
+ drive = self.env.scene.create_drive(
561
+ parent_link,
562
+ pose_in_parent,
563
+ self._object_component,
564
+ sapien.Pose(),
565
+ )
566
+ stiffness = float(self.settings.grasp_drive_stiffness)
567
+ damping = float(self.settings.grasp_drive_damping)
568
+ force_limit = float(self.settings.grasp_drive_force_limit)
569
+ for axis in ("x", "y", "z"):
570
+ getattr(drive, f"set_drive_property_{axis}")(
571
+ stiffness,
572
+ damping,
573
+ force_limit,
574
+ "acceleration",
575
+ )
576
+ drive.set_drive_property_slerp(
577
+ stiffness,
578
+ damping,
579
+ force_limit,
580
+ "acceleration",
581
+ )
582
+ limit_epsilon = float(self.settings.grasp_drive_limit_epsilon)
583
+ for axis in ("x", "y", "z"):
584
+ getattr(drive, f"set_limit_{axis}")(
585
+ -limit_epsilon, limit_epsilon
586
+ )
587
+ drive.set_limit_twist(-limit_epsilon, limit_epsilon)
588
+ drive.set_limit_cone(limit_epsilon, limit_epsilon)
589
+ drive.set_drive_target(sapien.Pose())
590
+ self._grasp_drive = drive
591
+ print(
592
+ "[dynamic-follow] verified bilateral grasp drive: "
593
+ f"{self._grasp_contact_links}"
594
+ )
595
+
596
+ def observe_target(self, offset: np.ndarray, quaternion: np.ndarray) -> np.ndarray:
597
+ object_position = self._object_position()
598
+ velocity = self.observer.observe(object_position, self.sim_step)
599
+ predicted_position = (
600
+ object_position
601
+ + np.asarray(offset, dtype=np.float64)
602
+ + self.settings.prediction_horizon_seconds * velocity
603
+ )
604
+ self.target_pose = np.concatenate([predicted_position, quaternion])
605
+ return self.target_pose.copy()
606
+
607
+ def plan(self, target_pose: np.ndarray) -> dict[str, Any]:
608
+ planner = (self.env.robot.right_plan_path if self.arm == "right"
609
+ else self.env.robot.left_plan_path)
610
+ result = planner(target_pose.tolist())
611
+ if result.get("status") == "Success":
612
+ return result
613
+
614
+ # A failed predictive goal is retried at the current (non-extrapolated)
615
+ # object position. This is still an online goal, not an intercept point.
616
+ fallback = target_pose.copy()
617
+ fallback[:3] -= self.settings.prediction_horizon_seconds * self.observer.velocity
618
+ self.target_pose = fallback
619
+ result = planner(fallback.tolist())
620
+ if result.get("status") != "Success":
621
+ raise RuntimeError(
622
+ f"{self.arm} planner failed during {self.stage}"
623
+ )
624
+ return result
625
+
626
+ def execute_plan_prefix(
627
+ self,
628
+ result: dict[str, Any],
629
+ max_steps: int,
630
+ close_progress: tuple[int, int] | None = None,
631
+ ) -> int:
632
+ positions = np.asarray(result["position"])
633
+ velocities = np.asarray(result["velocity"])
634
+ count = min(int(max_steps), len(positions))
635
+ if count <= 0:
636
+ raise RuntimeError("Planner returned an empty trajectory")
637
+ for index in range(count):
638
+ self.env.robot.set_arm_joints(positions[index], velocities[index], self.arm)
639
+ gripper = None
640
+ if close_progress is not None:
641
+ done, total = close_progress
642
+ fraction = min(1.0, (done + index + 1) / max(total, 1))
643
+ # Smooth closing avoids a visual/physical discontinuity.
644
+ smooth = fraction * fraction * (3.0 - 2.0 * fraction)
645
+ gripper = 1.0 - smooth
646
+ if (not self._released
647
+ and fraction >= self.settings.release_fraction):
648
+ self.release_to_contact_dynamics()
649
+ self.step(gripper_value=gripper)
650
+ return count
651
+
652
+ def _joint_goal_from_plan(self, result: dict[str, Any]) -> np.ndarray:
653
+ positions = np.asarray(result["position"], dtype=np.float64)
654
+ if positions.ndim != 2 or len(positions) == 0:
655
+ raise RuntimeError("Planner returned an invalid trajectory")
656
+ return positions[-1].copy()
657
+
658
+ def execute_smooth_servo(
659
+ self,
660
+ joint_goal: np.ndarray,
661
+ steps: int,
662
+ close_progress: tuple[int, int] | None = None,
663
+ fixed_gripper: float | None = None,
664
+ max_joint_velocity: float | None = None,
665
+ max_joint_acceleration: float | None = None,
666
+ ) -> int:
667
+ """Track a joint goal without resetting velocity at replans.
668
+
669
+ CuRobo supplies only a reachable goal. This acceleration-limited
670
+ servo owns execution and carries its velocity state across every
671
+ online target update, removing the stop/start boundary conditions of
672
+ point-to-point motion plans.
673
+ """
674
+
675
+ joint_goal = np.asarray(joint_goal, dtype=np.float64)
676
+ if self._servo_position is None:
677
+ self._servo_position = self._arm_joint_position()
678
+ self._servo_velocity = np.zeros_like(self._servo_position)
679
+
680
+ count = max(0, int(steps))
681
+ max_velocity = float(
682
+ self.settings.servo_max_joint_velocity
683
+ if max_joint_velocity is None else max_joint_velocity
684
+ )
685
+ max_accel_step = float(
686
+ (
687
+ self.settings.servo_max_joint_acceleration
688
+ if max_joint_acceleration is None else max_joint_acceleration
689
+ )
690
+ * self.dt
691
+ )
692
+ max_lead = float(self.settings.servo_max_position_lead)
693
+
694
+ for index in range(count):
695
+ actual = self._arm_joint_position()
696
+ error = joint_goal - actual
697
+ desired_velocity = np.clip(
698
+ self.settings.servo_position_gain * error,
699
+ -max_velocity,
700
+ max_velocity,
701
+ )
702
+ velocity_delta = np.clip(
703
+ desired_velocity - self._servo_velocity,
704
+ -max_accel_step,
705
+ max_accel_step,
706
+ )
707
+ self._servo_velocity += velocity_delta
708
+ next_position = self._servo_position + self._servo_velocity * self.dt
709
+ # Do not let the high-stiffness drive target run far ahead of the
710
+ # physical articulation when contact or inertia causes lag.
711
+ next_position = actual + np.clip(
712
+ next_position - actual, -max_lead, max_lead
713
+ )
714
+ self._servo_position = next_position
715
+ self.env.robot.set_arm_joints(
716
+ self._servo_position, self._servo_velocity, self.arm
717
+ )
718
+
719
+ gripper = fixed_gripper
720
+ if close_progress is not None:
721
+ done, total = close_progress
722
+ fraction = min(1.0, (done + index + 1) / max(total, 1))
723
+ smooth = fraction * fraction * (3.0 - 2.0 * fraction)
724
+ gripper = 1.0 - smooth
725
+ if (not self._released
726
+ and fraction >= self.settings.release_fraction):
727
+ self.release_to_contact_dynamics()
728
+ self.step(gripper_value=gripper)
729
+ return count
730
+
731
+ def smooth_track_until(
732
+ self,
733
+ offset: np.ndarray,
734
+ quaternion: np.ndarray,
735
+ tolerance: float,
736
+ max_cycles: int,
737
+ ) -> None:
738
+ for cycle in range(max_cycles):
739
+ target = self.observe_target(offset, quaternion)
740
+ # The predicted target is a feed-forward control lead. Arrival,
741
+ # however, must be judged against the object's pose *now*; using
742
+ # the lead point as the stopping condition makes a correctly
743
+ # tracking hand chase an intentionally moving goal indefinitely.
744
+ current_target = (
745
+ target[:3]
746
+ - self.settings.prediction_horizon_seconds
747
+ * self.observer.velocity
748
+ )
749
+ distance = float(
750
+ np.linalg.norm(self._ee_pose()[:3] - current_target)
751
+ )
752
+ if distance <= tolerance:
753
+ return
754
+ result = self.plan(target)
755
+ joint_goal = self._joint_goal_from_plan(result)
756
+ print(
757
+ f"[dynamic-follow] smooth stage={self.stage} cycle={cycle} "
758
+ f"current_error={distance:.3f}m "
759
+ f"execute={self.settings.servo_replan_steps}"
760
+ )
761
+ self.execute_smooth_servo(
762
+ joint_goal, self.settings.servo_replan_steps
763
+ )
764
+ current_target = (
765
+ self.target_pose[:3]
766
+ - self.settings.prediction_horizon_seconds
767
+ * self.observer.velocity
768
+ )
769
+ final_distance = float(
770
+ np.linalg.norm(self._ee_pose()[:3] - current_target)
771
+ )
772
+ raise RuntimeError(
773
+ f"{self.stage} did not converge: final EE target error={final_distance:.3f} m"
774
+ )
775
+
776
+ def smooth_follow_for(
777
+ self,
778
+ offset: np.ndarray,
779
+ quaternion: np.ndarray,
780
+ seconds: float,
781
+ ) -> None:
782
+ remaining = max(1, round(seconds / self.dt))
783
+ while remaining > 0:
784
+ target = self.observe_target(offset, quaternion)
785
+ result = self.plan(target)
786
+ count = min(self.settings.servo_replan_steps, remaining)
787
+ self.execute_smooth_servo(self._joint_goal_from_plan(result), count)
788
+ remaining -= count
789
+
790
+ def smooth_close_while_following(
791
+ self,
792
+ offset: np.ndarray,
793
+ quaternion: np.ndarray,
794
+ ) -> None:
795
+ total = max(1, round(self.settings.close_seconds / self.dt))
796
+ done = 0
797
+ while done < total:
798
+ target = self.observe_target(offset, quaternion)
799
+ result = self.plan(target)
800
+ count = min(self.settings.servo_replan_steps, total - done)
801
+ self.execute_smooth_servo(
802
+ self._joint_goal_from_plan(result),
803
+ count,
804
+ close_progress=(done, total),
805
+ )
806
+ done += count
807
+ self.release_to_contact_dynamics()
808
+
809
+ def smooth_lift(self) -> None:
810
+ start = self._ee_pose().copy()
811
+ start_rotation = t3d.quaternions.quat2mat(start[3:])
812
+ # Match Base_Task.move_by_displacement(..., move_axis="arm"): for
813
+ # this side grasp, negative tool-x is the gripper's natural upward
814
+ # withdrawal direction and is more reachable than forcing world-z.
815
+ lift_direction = -start_rotation[:, 0]
816
+ lift_direction /= max(np.linalg.norm(lift_direction), 1e-12)
817
+ final_target = start.copy()
818
+ final_target[:3] += self.settings.lift_height * lift_direction
819
+ # The lift target is static once the grasp is secured. Clear the
820
+ # motion predictor so a planner retry is not shifted sideways by the
821
+ # bottle's obsolete pre-grasp velocity estimate.
822
+ self.observer.velocity[:] = 0.0
823
+
824
+ # Two shorter plans are substantially easier for CuRobo than one
825
+ # 14-cm jump near the table, while preserving the same total height
826
+ # and two-second control budget.
827
+ max_steps = max(2, round(2.0 / self.dt))
828
+ stage_steps = max(1, max_steps // 2)
829
+ chunk = self.settings.servo_replan_steps
830
+ for fraction in (0.5, 1.0):
831
+ target = start.copy()
832
+ target[:3] += (
833
+ self.settings.lift_height * fraction * lift_direction
834
+ )
835
+ self.target_pose = target.copy()
836
+ result = self.plan(target)
837
+ joint_goal = self._joint_goal_from_plan(result)
838
+ remaining = stage_steps
839
+ while remaining > 0:
840
+ distance = float(
841
+ np.linalg.norm(self._ee_pose()[:3] - target[:3])
842
+ )
843
+ if distance <= 0.012:
844
+ break
845
+ count = min(chunk, remaining)
846
+ self.execute_smooth_servo(
847
+ joint_goal, count, fixed_gripper=0.0
848
+ )
849
+ remaining -= count
850
+
851
+ distance = float(
852
+ np.linalg.norm(self._ee_pose()[:3] - final_target[:3])
853
+ )
854
+ if distance > 0.025:
855
+ raise RuntimeError(f"smooth lift did not converge: error={distance:.3f} m")
856
+
857
+ @staticmethod
858
+ def quaternion_error_degrees(
859
+ quaternion: np.ndarray,
860
+ target_quaternion: np.ndarray,
861
+ ) -> float:
862
+ quaternion = np.asarray(quaternion, dtype=np.float64)
863
+ target_quaternion = np.asarray(target_quaternion, dtype=np.float64)
864
+ quaternion /= max(np.linalg.norm(quaternion), 1e-12)
865
+ target_quaternion /= max(np.linalg.norm(target_quaternion), 1e-12)
866
+ cosine = float(np.clip(abs(np.dot(quaternion, target_quaternion)), 0.0, 1.0))
867
+ return float(np.degrees(2.0 * np.arccos(cosine)))
868
+
869
+ @staticmethod
870
+ def quaternion_z_axis(quaternion: np.ndarray) -> np.ndarray:
871
+ """Return the world-space local-z axis for a wxyz quaternion."""
872
+
873
+ quaternion = np.asarray(quaternion, dtype=np.float64)
874
+ quaternion /= max(np.linalg.norm(quaternion), 1e-12)
875
+ w, x, y, z = quaternion
876
+ return np.asarray(
877
+ [
878
+ 2.0 * (x * z + w * y),
879
+ 2.0 * (y * z - w * x),
880
+ 1.0 - 2.0 * (x * x + y * y),
881
+ ],
882
+ dtype=np.float64,
883
+ )
884
+
885
+ @classmethod
886
+ def upright_axis_error_degrees(
887
+ cls,
888
+ quaternion: np.ndarray,
889
+ target_quaternion: np.ndarray,
890
+ ) -> float:
891
+ axis = cls.quaternion_z_axis(quaternion)
892
+ target_axis = cls.quaternion_z_axis(target_quaternion)
893
+ cosine = float(np.clip(np.dot(axis, target_axis), -1.0, 1.0))
894
+ return float(np.degrees(np.arccos(cosine)))
895
+
896
+ def smooth_place_upright(self) -> np.ndarray:
897
+ """Carry the grasped bottle to the original task's upright side pose."""
898
+
899
+ task_target = np.asarray(
900
+ self.env.right_target_pose if self.arm == "right"
901
+ else self.env.left_target_pose,
902
+ dtype=np.float64,
903
+ )
904
+ ee_start = self._ee_pose()
905
+ functional_start = self.env.bottle.get_functional_point(0, "pose")
906
+ functional_start_position = np.asarray(
907
+ functional_start.p, dtype=np.float64
908
+ )
909
+ functional_start_rotation = t3d.quaternions.quat2mat(
910
+ np.asarray(functional_start.q, dtype=np.float64)
911
+ )
912
+ ee_target = np.asarray(
913
+ self.env.get_place_pose(
914
+ self.env.bottle,
915
+ ArmTag(self.arm),
916
+ task_target,
917
+ functional_point_id=0,
918
+ pre_dis=0.0,
919
+ ),
920
+ dtype=np.float64,
921
+ )
922
+
923
+ # get_place_pose(auto) aligns the bottle using the grasp direction.
924
+ # Recover that actual functional-point target from the same rigid EE
925
+ # transform instead of comparing against task_target's raw quaternion.
926
+ ee_start_rotation = t3d.quaternions.quat2mat(ee_start[3:])
927
+ ee_target_rotation = t3d.quaternions.quat2mat(ee_target[3:])
928
+ start_to_target_rotation = (
929
+ ee_target_rotation @ ee_start_rotation.T
930
+ )
931
+ functional_target_position = (
932
+ ee_target[:3]
933
+ + start_to_target_rotation
934
+ @ (functional_start_position - ee_start[:3])
935
+ )
936
+ functional_target_quaternion = t3d.quaternions.mat2quat(
937
+ start_to_target_rotation @ functional_start_rotation
938
+ )
939
+ functional_target = np.concatenate(
940
+ [functional_target_position, functional_target_quaternion]
941
+ )
942
+ self.target_pose = ee_target.copy()
943
+ # This target is static and unrelated to the earlier motion predictor.
944
+ self.observer.velocity[:] = 0.0
945
+ result = self.plan(ee_target)
946
+ joint_goal = self._joint_goal_from_plan(result)
947
+ remaining = max(1, round(self.settings.place_max_seconds / self.dt))
948
+ chunk = self.settings.servo_replan_steps
949
+ while remaining > 0:
950
+ ee_pose = self._ee_pose()
951
+ position_error = float(np.linalg.norm(ee_pose[:3] - ee_target[:3]))
952
+ orientation_error = self.quaternion_error_degrees(
953
+ ee_pose[3:], ee_target[3:]
954
+ )
955
+ if (
956
+ position_error
957
+ <= self.settings.place_control_position_tolerance
958
+ and orientation_error
959
+ <= self.settings.place_orientation_tolerance_degrees
960
+ ):
961
+ return functional_target
962
+ count = min(chunk, remaining)
963
+ self.execute_smooth_servo(
964
+ joint_goal,
965
+ count,
966
+ fixed_gripper=0.0,
967
+ max_joint_velocity=self.settings.place_max_joint_velocity,
968
+ max_joint_acceleration=self.settings.place_max_joint_acceleration,
969
+ )
970
+ remaining -= count
971
+
972
+ ee_pose = self._ee_pose()
973
+ position_error = float(np.linalg.norm(ee_pose[:3] - ee_target[:3]))
974
+ orientation_error = self.quaternion_error_degrees(
975
+ ee_pose[3:], ee_target[3:]
976
+ )
977
+ # The last servo chunk can be the one that crosses both tolerances.
978
+ # Re-check after it executes instead of unconditionally rejecting an
979
+ # otherwise valid trajectory when the step budget reaches zero. At
980
+ # this terminal fallback, allow the task's upright tolerance: the
981
+ # definitive check below is performed on the bottle's functional
982
+ # point, where yaw around its upright axis is intentionally irrelevant.
983
+ if (
984
+ position_error <= self.settings.place_position_tolerance
985
+ and orientation_error
986
+ <= self.settings.upright_axis_tolerance_degrees
987
+ ):
988
+ return functional_target
989
+ raise RuntimeError(
990
+ "smooth upright placement did not converge: "
991
+ f"position_error={position_error:.3f}m "
992
+ f"orientation_error={orientation_error:.1f}deg"
993
+ )
994
+
995
+ def smooth_settle(self, seconds: float) -> None:
996
+ # Braking is acceleration limited as well; no final velocity snap.
997
+ goal = self._arm_joint_position()
998
+ self.execute_smooth_servo(
999
+ goal, round(seconds / self.dt), fixed_gripper=0.0
1000
+ )
1001
+
1002
+ def track_until(
1003
+ self,
1004
+ offset: np.ndarray,
1005
+ quaternion: np.ndarray,
1006
+ tolerance: float,
1007
+ max_cycles: int,
1008
+ ) -> None:
1009
+ for cycle in range(max_cycles):
1010
+ target = self.observe_target(offset, quaternion)
1011
+ distance = float(np.linalg.norm(self._ee_pose()[:3] - target[:3]))
1012
+ if distance <= tolerance:
1013
+ return
1014
+ result = self.plan(target)
1015
+ if distance > 0.12:
1016
+ horizon = self.settings.catchup_horizon_steps
1017
+ elif distance > 0.06:
1018
+ horizon = self.settings.medium_horizon_steps
1019
+ else:
1020
+ horizon = self.settings.replanning_horizon_steps
1021
+ horizon = min(horizon, len(result["position"]))
1022
+ print(
1023
+ f"[dynamic-follow] stage={self.stage} cycle={cycle} "
1024
+ f"error={distance:.3f}m plan={len(result['position'])} "
1025
+ f"execute={horizon}"
1026
+ )
1027
+ self.execute_plan_prefix(result, horizon)
1028
+ final_distance = float(np.linalg.norm(self._ee_pose()[:3] - self.target_pose[:3]))
1029
+ raise RuntimeError(
1030
+ f"{self.stage} did not converge: final EE target error={final_distance:.3f} m"
1031
+ )
1032
+
1033
+ def follow_for(
1034
+ self,
1035
+ offset: np.ndarray,
1036
+ quaternion: np.ndarray,
1037
+ seconds: float,
1038
+ ) -> None:
1039
+ remaining = max(1, round(seconds / self.dt))
1040
+ while remaining > 0:
1041
+ target = self.observe_target(offset, quaternion)
1042
+ result = self.plan(target)
1043
+ executed = self.execute_plan_prefix(
1044
+ result, min(self.settings.replanning_horizon_steps, remaining)
1045
+ )
1046
+ remaining -= executed
1047
+
1048
+ def close_while_following(
1049
+ self,
1050
+ offset: np.ndarray,
1051
+ quaternion: np.ndarray,
1052
+ ) -> None:
1053
+ total = max(1, round(self.settings.close_seconds / self.dt))
1054
+ done = 0
1055
+ while done < total:
1056
+ target = self.observe_target(offset, quaternion)
1057
+ result = self.plan(target)
1058
+ executed = self.execute_plan_prefix(
1059
+ result,
1060
+ min(self.settings.replanning_horizon_steps, total - done),
1061
+ close_progress=(done, total),
1062
+ )
1063
+ done += executed
1064
+ self.release_to_contact_dynamics()
1065
+
1066
+ def lift(self) -> None:
1067
+ current = self._ee_pose()
1068
+ target = current.copy()
1069
+ target[2] += self.settings.lift_height
1070
+ self.target_pose = target
1071
+ result = self.plan(target)
1072
+ self.execute_plan_prefix(result, len(result["position"]))
1073
+
1074
+ def run(self) -> dict[str, Any]:
1075
+ arm_tag = ArmTag(self.arm)
1076
+ grasp_reference_position = self._object_position()
1077
+
1078
+ # Select a feasible grasp once. Afterwards only its rigid offset and
1079
+ # orientation are reused; the world target is recomputed online.
1080
+ pre_pose, grasp_pose = self.env.choose_grasp_pose(
1081
+ self.env.bottle,
1082
+ arm_tag=arm_tag,
1083
+ pre_dis=self.settings.pre_grasp_distance,
1084
+ target_dis=0.0,
1085
+ )
1086
+ if pre_pose is None or grasp_pose is None:
1087
+ raise RuntimeError("No feasible grasp pose")
1088
+ pre_pose = np.asarray(pre_pose, dtype=np.float64)
1089
+ grasp_pose = np.asarray(grasp_pose, dtype=np.float64)
1090
+ pre_offset = pre_pose[:3] - grasp_reference_position
1091
+ grasp_offset = grasp_pose[:3] - grasp_reference_position
1092
+ quaternion = grasp_pose[3:].copy()
1093
+
1094
+ if self.settings.offscreen_start_x > 0:
1095
+ pose = self.env.bottle.get_pose()
1096
+ start_x = (self.settings.offscreen_start_x
1097
+ if self.arm == "right"
1098
+ else -self.settings.offscreen_start_x)
1099
+ start_position = np.asarray(pose.p, dtype=np.float64)
1100
+ start_position[0] = start_x
1101
+ self.env.bottle.actor.set_pose(
1102
+ sapien.Pose(p=start_position, q=pose.q)
1103
+ )
1104
+
1105
+ initial_object_position = self._object_position()
1106
+ initial_object_quaternion = np.asarray(
1107
+ self.env.bottle.get_pose().q, dtype=np.float64
1108
+ )
1109
+ # Enter from the side assigned to the grasping arm.
1110
+ x_direction = -1.0 if self.arm == "right" else 1.0
1111
+ initial_velocity = np.array(
1112
+ [x_direction * self.settings.speed_x, self.settings.speed_y, 0.0],
1113
+ dtype=np.float64,
1114
+ )
1115
+
1116
+ self.observer.observe(initial_object_position, self.sim_step)
1117
+ self.stage = "object_only"
1118
+ self.target_pose[:] = np.nan
1119
+ self._capture()
1120
+ self.start_independent_motion(initial_velocity)
1121
+ self.hold(round(self.settings.object_only_seconds / self.dt))
1122
+
1123
+ self.stage = "approach_follow"
1124
+ if self.settings.controller_mode == "smooth_joint_servo":
1125
+ self.smooth_track_until(
1126
+ pre_offset,
1127
+ quaternion,
1128
+ self.settings.approach_tolerance,
1129
+ self.settings.max_approach_cycles,
1130
+ )
1131
+ else:
1132
+ self.track_until(
1133
+ pre_offset,
1134
+ quaternion,
1135
+ self.settings.approach_tolerance,
1136
+ self.settings.max_approach_cycles,
1137
+ )
1138
+
1139
+ self.stage = "follow_above"
1140
+ if self.settings.controller_mode == "smooth_joint_servo":
1141
+ self.smooth_follow_for(
1142
+ pre_offset, quaternion, self.settings.follow_hold_seconds
1143
+ )
1144
+ else:
1145
+ self.follow_for(pre_offset, quaternion, self.settings.follow_hold_seconds)
1146
+
1147
+ self.stage = "descend_follow"
1148
+ if self.settings.controller_mode == "smooth_joint_servo":
1149
+ self.smooth_track_until(
1150
+ grasp_offset,
1151
+ quaternion,
1152
+ self.settings.grasp_tolerance,
1153
+ self.settings.max_descend_cycles,
1154
+ )
1155
+ else:
1156
+ self.track_until(
1157
+ grasp_offset,
1158
+ quaternion,
1159
+ self.settings.grasp_tolerance,
1160
+ self.settings.max_descend_cycles,
1161
+ )
1162
+
1163
+ self.stage = "close_follow"
1164
+ if self.settings.controller_mode == "smooth_joint_servo":
1165
+ self.smooth_close_while_following(grasp_offset, quaternion)
1166
+ else:
1167
+ self.close_while_following(grasp_offset, quaternion)
1168
+
1169
+ if self.settings.grasp_settle_seconds > 0:
1170
+ self.stage = "grasp_settle"
1171
+ if self.settings.controller_mode == "smooth_joint_servo":
1172
+ self.smooth_settle(self.settings.grasp_settle_seconds)
1173
+ else:
1174
+ self.hold(
1175
+ round(self.settings.grasp_settle_seconds / self.dt),
1176
+ gripper_value=0.0,
1177
+ )
1178
+
1179
+ if self.settings.stabilize_grasp_with_drive:
1180
+ self.attach_verified_grasp_drive()
1181
+
1182
+ self.stage = "lift"
1183
+ before_lift = self._object_position()
1184
+ if self.settings.controller_mode == "smooth_joint_servo":
1185
+ self.smooth_lift()
1186
+ else:
1187
+ self.lift()
1188
+
1189
+ functional_target_pose: np.ndarray | None = None
1190
+ if self.settings.complete_original_task:
1191
+ self.stage = "upright_place"
1192
+ functional_target_pose = self.smooth_place_upright()
1193
+
1194
+ self.stage = "settle"
1195
+ self.target_pose[:] = np.nan
1196
+ if self.settings.controller_mode == "smooth_joint_servo":
1197
+ self.smooth_settle(self.settings.settle_seconds)
1198
+ else:
1199
+ self.hold(round(self.settings.settle_seconds / self.dt), gripper_value=0.0)
1200
+ self._capture()
1201
+
1202
+ final_object_position = self._object_position()
1203
+ final_ee_position = self._ee_pose()[:3]
1204
+ object_motion = float(
1205
+ np.linalg.norm(before_lift[:2] - initial_object_position[:2])
1206
+ )
1207
+ lift_delta = float(final_object_position[2] - before_lift[2])
1208
+ final_object_ee_distance = float(
1209
+ np.linalg.norm(final_object_position - final_ee_position)
1210
+ )
1211
+ functional_pose = self.env.bottle.get_functional_point(0, "pose")
1212
+ final_functional_position = np.asarray(
1213
+ functional_pose.p, dtype=np.float64
1214
+ )
1215
+ original_task_success: bool | None = None
1216
+ upright_error_degrees: float | None = None
1217
+ upright_axis_error_degrees: float | None = None
1218
+ placement_position_error: float | None = None
1219
+ final_functional_quaternion = np.asarray(
1220
+ functional_pose.q, dtype=np.float64
1221
+ )
1222
+ if functional_target_pose is not None:
1223
+ original_task_success = bool(self.env.check_success())
1224
+ placement_position_error = float(
1225
+ np.linalg.norm(
1226
+ final_functional_position - functional_target_pose[:3]
1227
+ )
1228
+ )
1229
+ upright_error_degrees = self.quaternion_error_degrees(
1230
+ final_functional_quaternion,
1231
+ functional_target_pose[3:],
1232
+ )
1233
+ upright_axis_error_degrees = self.upright_axis_error_degrees(
1234
+ final_functional_quaternion,
1235
+ functional_target_pose[3:],
1236
+ )
1237
+
1238
+ grasp_quality = bool(
1239
+ object_motion >= 0.045
1240
+ # This repository's EE pose is behind the finger center by roughly
1241
+ # 12 cm, so a successfully enclosed bottle naturally has an
1242
+ # object-to-EE distance around 18 cm for this side grasp.
1243
+ and final_object_ee_distance <= 0.22
1244
+ )
1245
+ if self.settings.complete_original_task:
1246
+ success = bool(
1247
+ grasp_quality
1248
+ and original_task_success
1249
+ and placement_position_error is not None
1250
+ and placement_position_error
1251
+ <= self.settings.place_position_tolerance
1252
+ and upright_axis_error_degrees is not None
1253
+ and upright_axis_error_degrees
1254
+ <= self.settings.upright_axis_tolerance_degrees
1255
+ )
1256
+ else:
1257
+ success = bool(grasp_quality and lift_delta >= 0.055)
1258
+ return {
1259
+ "success": success,
1260
+ "controller_mode": self.settings.controller_mode,
1261
+ "arm": self.arm,
1262
+ "object_model_id": int(self.env.model_id),
1263
+ "grasp_reference_position": grasp_reference_position.tolist(),
1264
+ "initial_object_position": initial_object_position.tolist(),
1265
+ "initial_object_quaternion": initial_object_quaternion.tolist(),
1266
+ "initial_velocity": initial_velocity.tolist(),
1267
+ "object_motion_before_lift_m": object_motion,
1268
+ "lift_delta_m": lift_delta,
1269
+ "final_object_ee_distance_m": final_object_ee_distance,
1270
+ "final_functional_point_position": final_functional_position.tolist(),
1271
+ "final_functional_point_quaternion": final_functional_quaternion.tolist(),
1272
+ "original_task_success": original_task_success,
1273
+ "placement_position_error_m": placement_position_error,
1274
+ "full_orientation_error_degrees": upright_error_degrees,
1275
+ "upright_axis_error_degrees": upright_axis_error_degrees,
1276
+ "held_friction_shape_count": len(self._held_shape_materials),
1277
+ "held_friction_actor_names": sorted(
1278
+ self._held_friction_actor_names
1279
+ ),
1280
+ "grasp_constraint_used": self._grasp_drive is not None,
1281
+ "grasp_contact_links": self._grasp_contact_links,
1282
+ "upright_target_pose": (
1283
+ None if functional_target_pose is None
1284
+ else functional_target_pose.tolist()
1285
+ ),
1286
+ "duration_seconds": self.sim_step * self.dt,
1287
+ "sim_steps": self.sim_step,
1288
+ "frames": self.env.FRAME_IDX,
1289
+ }
1290
+
1291
+ def save_trace(self, path: Path) -> None:
1292
+ path.parent.mkdir(parents=True, exist_ok=True)
1293
+ arrays: dict[str, np.ndarray] = {}
1294
+ for key, values in self.records.items():
1295
+ if key == "stage":
1296
+ arrays[key] = np.asarray(values, dtype="U24")
1297
+ else:
1298
+ arrays[key] = np.asarray(values)
1299
+ np.savez_compressed(path, **arrays)
1300
+
1301
+
1302
+ def load_config(path: Path) -> dict[str, Any]:
1303
+ with path.open("r", encoding="utf-8") as handle:
1304
+ args = yaml.load(handle, Loader=yaml.FullLoader)
1305
+
1306
+ embodiment = args["embodiment"]
1307
+ if len(embodiment) != 1:
1308
+ raise ValueError("This preview collector currently expects one dual-arm embodiment")
1309
+ with (Path(CONFIGS_PATH) / "_embodiment_config.yml").open(
1310
+ "r", encoding="utf-8"
1311
+ ) as handle:
1312
+ embodiment_types = yaml.load(handle, Loader=yaml.FullLoader)
1313
+ robot_file = embodiment_types[embodiment[0]]["file_path"]
1314
+ with (Path(robot_file) / "config.yml").open("r", encoding="utf-8") as handle:
1315
+ robot_config = yaml.load(handle, Loader=yaml.FullLoader)
1316
+
1317
+ args.update(
1318
+ task_name="adjust_bottle",
1319
+ task_config=path.stem,
1320
+ left_robot_file=robot_file,
1321
+ right_robot_file=robot_file,
1322
+ left_embodiment_config=robot_config,
1323
+ right_embodiment_config=robot_config,
1324
+ dual_arm_embodied=True,
1325
+ need_plan=True,
1326
+ save_data=True,
1327
+ use_dynamic=False,
1328
+ render_freq=0,
1329
+ record_native_timestamps=True,
1330
+ )
1331
+ args["save_path"] = str(
1332
+ REPO_ROOT / args["save_path"] / args["task_name"] / args["task_config"]
1333
+ )
1334
+ return args
1335
+
1336
+
1337
+ def remove_episode_cache(output_dir: Path, episode: int) -> None:
1338
+ cache = output_dir / ".cache" / f"episode{episode}"
1339
+ if cache.is_dir():
1340
+ shutil.rmtree(cache)
1341
+
1342
+
1343
+ def write_collection_summary(path: Path, payload: dict[str, Any]) -> None:
1344
+ """Atomically checkpoint collection progress after every attempt."""
1345
+
1346
+ temporary = path.with_suffix(".json.tmp")
1347
+ with temporary.open("w", encoding="utf-8") as handle:
1348
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
1349
+ os.replace(temporary, path)
1350
+
1351
+
1352
+ def write_standard_dataset_metadata(
1353
+ output_dir: Path, summaries: list[dict[str, Any]]
1354
+ ) -> None:
1355
+ """Write metadata expected by the repository's training converters.
1356
+
1357
+ The stock collector obtains this information from ``env.info``. This
1358
+ online collector instead reconstructs the same minimal schema from the
1359
+ accepted episode summaries, which also makes resumed and merged datasets
1360
+ deterministic.
1361
+ """
1362
+
1363
+ scene_info: dict[str, dict[str, dict[str, str]]] = {}
1364
+ seeds: list[str] = []
1365
+ for expected_episode, summary in enumerate(summaries):
1366
+ episode = int(summary.get("episode", -1))
1367
+ if episode != expected_episode:
1368
+ raise RuntimeError(
1369
+ "Cannot write dataset metadata for non-contiguous episodes: "
1370
+ f"expected {expected_episode}, got {episode}"
1371
+ )
1372
+ arm = str(summary["arm"])
1373
+ if arm not in {"left", "right"}:
1374
+ raise ValueError(f"Unsupported arm in episode summary: {arm}")
1375
+ model_id = int(summary["object_model_id"])
1376
+ if model_id not in {13, 16}:
1377
+ raise ValueError(
1378
+ f"Unsupported adjust_bottle model id in summary: {model_id}"
1379
+ )
1380
+ scene_info[f"episode_{episode}"] = {
1381
+ "info": {
1382
+ "{A}": f"001_bottle/base{model_id}",
1383
+ "{a}": arm,
1384
+ }
1385
+ }
1386
+ seeds.append(str(int(summary["seed"])))
1387
+
1388
+ scene_path = output_dir / "scene_info.json"
1389
+ scene_temporary = scene_path.with_suffix(".json.tmp")
1390
+ with scene_temporary.open("w", encoding="utf-8") as handle:
1391
+ json.dump(scene_info, handle, ensure_ascii=False, indent=2)
1392
+ os.replace(scene_temporary, scene_path)
1393
+
1394
+ seed_path = output_dir / "seed.txt"
1395
+ seed_temporary = seed_path.with_suffix(".txt.tmp")
1396
+ seed_temporary.write_text(" ".join(seeds) + "\n", encoding="utf-8")
1397
+ os.replace(seed_temporary, seed_path)
1398
+
1399
+
1400
+ def collect(
1401
+ args: dict[str, Any],
1402
+ episodes: int,
1403
+ seed_start: int,
1404
+ resume: bool = False,
1405
+ ) -> Path:
1406
+ output_dir = Path(args["save_path"])
1407
+ output_dir.mkdir(parents=True, exist_ok=True)
1408
+ (output_dir / "metrics").mkdir(parents=True, exist_ok=True)
1409
+ base_settings = FollowSettings.from_dict(args.get("dynamic_follow"))
1410
+ distribution = FollowDistributionSettings.from_dict(
1411
+ args.get("dynamic_follow_distribution")
1412
+ )
1413
+ schedule = build_follow_schedule(base_settings, distribution)
1414
+ if distribution.enabled and episodes > len(schedule):
1415
+ raise ValueError(
1416
+ f"Requested {episodes} episodes but the distribution schedule has "
1417
+ f"only {len(schedule)} entries"
1418
+ )
1419
+ max_attempts = int(args.get("max_attempts", max(episodes * 8, 10)))
1420
+
1421
+ summary_path = output_dir / "summary.json"
1422
+ summaries: list[dict[str, Any]] = []
1423
+ failures: list[dict[str, Any]] = []
1424
+ attempted_seeds: list[int] = []
1425
+ collection_phases: list[dict[str, Any]] = []
1426
+ settings_phases: list[dict[str, Any]] = []
1427
+ attempts = 0
1428
+ if resume and summary_path.is_file():
1429
+ with summary_path.open("r", encoding="utf-8") as handle:
1430
+ checkpoint = json.load(handle)
1431
+ summaries = list(checkpoint.get("episodes", []))
1432
+ failures = list(checkpoint.get("failures", []))
1433
+ attempted_seeds = [
1434
+ int(seed) for seed in checkpoint.get("attempted_seeds", [])
1435
+ ]
1436
+ attempts = int(checkpoint.get("attempts", len(attempted_seeds)))
1437
+ collection_phases = list(checkpoint.get("collection_phases", []))
1438
+ settings_phases = list(checkpoint.get("settings_phases", []))
1439
+ if attempts != len(attempted_seeds):
1440
+ raise RuntimeError(
1441
+ "Resume checkpoint has inconsistent attempts/attempted_seeds"
1442
+ )
1443
+ for expected_episode, summary in enumerate(summaries):
1444
+ if int(summary.get("episode", -1)) != expected_episode:
1445
+ raise RuntimeError("Resume checkpoint episodes are not contiguous")
1446
+ for relative in (
1447
+ Path("data") / f"episode{expected_episode}.hdf5",
1448
+ Path("video") / f"episode{expected_episode}.mp4",
1449
+ Path("metrics") / f"episode{expected_episode}.npz",
1450
+ ):
1451
+ if not (output_dir / relative).is_file():
1452
+ raise RuntimeError(
1453
+ f"Resume checkpoint references missing file: {relative}"
1454
+ )
1455
+ print(
1456
+ f"[dynamic-follow] resume {len(summaries)}/{episodes} episodes, "
1457
+ f"{attempts} attempts already consumed"
1458
+ )
1459
+
1460
+ # Older checkpoints predate explicit phase provenance. Preserve the
1461
+ # distribution that produced their already-written episodes before a
1462
+ # resumed run switches to a different (for example faster) profile.
1463
+ if summaries and not collection_phases:
1464
+ collection_phases.append(
1465
+ {
1466
+ "start_episode": 0,
1467
+ "start_attempt": 0,
1468
+ "distribution": checkpoint.get("distribution", {}),
1469
+ }
1470
+ )
1471
+ if summaries and not settings_phases:
1472
+ settings_phases.append(
1473
+ {
1474
+ "start_episode": 0,
1475
+ "start_attempt": 0,
1476
+ "settings": checkpoint.get("base_settings", {}),
1477
+ }
1478
+ )
1479
+
1480
+ current_distribution = dict(distribution.__dict__)
1481
+ if (
1482
+ not collection_phases
1483
+ or collection_phases[-1].get("distribution") != current_distribution
1484
+ ):
1485
+ collection_phases.append(
1486
+ {
1487
+ "start_episode": len(summaries),
1488
+ "start_attempt": attempts,
1489
+ "distribution": current_distribution,
1490
+ }
1491
+ )
1492
+ current_settings = dict(base_settings.__dict__)
1493
+ if (
1494
+ not settings_phases
1495
+ or settings_phases[-1].get("settings") != current_settings
1496
+ ):
1497
+ settings_phases.append(
1498
+ {
1499
+ "start_episode": len(summaries),
1500
+ "start_attempt": attempts,
1501
+ "settings": current_settings,
1502
+ }
1503
+ )
1504
+
1505
+ successful = len(summaries)
1506
+ configured_seeds = [int(value) for value in args.get("seed_list", [])]
1507
+ fallback_seed_start = max([int(seed_start), *configured_seeds]) + 1
1508
+ session_attempts = 0
1509
+ env = adjust_bottle()
1510
+
1511
+ def checkpoint_payload() -> dict[str, Any]:
1512
+ return {
1513
+ "method": "online approach-follow-grasp (DynamicVLA-style teacher)",
1514
+ "method_version": 2,
1515
+ "uses_precomputed_intercept": False,
1516
+ "uses_future_object_path": False,
1517
+ "complete": successful == episodes,
1518
+ "episodes_requested": episodes,
1519
+ "episodes_successful": successful,
1520
+ "attempts": attempts,
1521
+ "attempted_seeds": attempted_seeds,
1522
+ "base_settings": base_settings.__dict__,
1523
+ # Keep the historical field name for readers of preview summaries.
1524
+ "settings": base_settings.__dict__,
1525
+ "distribution": distribution.__dict__,
1526
+ "collection_phases": collection_phases,
1527
+ "settings_phases": settings_phases,
1528
+ "episodes": summaries,
1529
+ "failures": failures,
1530
+ }
1531
+
1532
+ write_collection_summary(summary_path, checkpoint_payload())
1533
+ write_standard_dataset_metadata(output_dir, summaries)
1534
+ while successful < episodes and attempts < max_attempts:
1535
+ if attempts < len(configured_seeds):
1536
+ seed = configured_seeds[attempts]
1537
+ else:
1538
+ seed = fallback_seed_start + attempts - len(configured_seeds)
1539
+ settings, sampling = schedule[successful] if distribution.enabled else schedule[0]
1540
+ controller: OnlineFollowEpisode | None = None
1541
+ episode_wall_start = time.perf_counter()
1542
+ print(
1543
+ f"\n[dynamic-follow] episode={successful} seed={seed} "
1544
+ f"attempt={attempts + 1}/{max_attempts} "
1545
+ f"speed={sampling['target_speed_mps']:.3f}m/s "
1546
+ f"angle={sampling['entry_angle_degrees']:+.1f}deg"
1547
+ )
1548
+ try:
1549
+ episode_args = dict(args)
1550
+ # CuRobo is robot-model based here and can be reused across scenes.
1551
+ # Base_Task would otherwise rebuild and warm it up for every seed.
1552
+ # Robot.reset keeps the existing CuRobo planners when skip_planner
1553
+ # is true, while still loading fresh articulation entities.
1554
+ planners_ready = (
1555
+ hasattr(getattr(env, "robot", None), "left_planner")
1556
+ and hasattr(getattr(env, "robot", None), "right_planner")
1557
+ )
1558
+ if session_attempts > 0 and planners_ready:
1559
+ episode_args["skip_planner"] = True
1560
+ env.setup_demo(now_ep_num=successful, seed=seed, **episode_args)
1561
+ controller = OnlineFollowEpisode(env, settings)
1562
+ summary = controller.run()
1563
+ summary.update(
1564
+ seed=seed,
1565
+ episode=successful,
1566
+ sampling=sampling,
1567
+ )
1568
+ if not summary["success"]:
1569
+ raise RuntimeError(f"trajectory quality check failed: {summary}")
1570
+
1571
+ trace_path = output_dir / "metrics" / f"episode{successful}.npz"
1572
+ controller.save_trace(trace_path)
1573
+ env.merge_pkl_to_hdf5_video()
1574
+ env.remove_data_cache()
1575
+ summary["collection_wall_seconds"] = (
1576
+ time.perf_counter() - episode_wall_start
1577
+ )
1578
+ summaries.append(summary)
1579
+ print("[dynamic-follow] success", json.dumps(summary, ensure_ascii=False))
1580
+ successful += 1
1581
+ except Exception as exc:
1582
+ if is_fatal_infrastructure_error(exc):
1583
+ print(
1584
+ "[dynamic-follow] fatal infrastructure error; aborting "
1585
+ f"without consuming seed={seed}: {type(exc).__name__}: {exc}"
1586
+ )
1587
+ remove_episode_cache(output_dir, successful)
1588
+ raise
1589
+ print(f"[dynamic-follow] failed seed={seed}: {type(exc).__name__}: {exc}")
1590
+ failures.append(
1591
+ {
1592
+ "attempt": attempts,
1593
+ "episode": successful,
1594
+ "seed": seed,
1595
+ "error_type": type(exc).__name__,
1596
+ "error": str(exc),
1597
+ }
1598
+ )
1599
+ remove_episode_cache(output_dir, successful)
1600
+ finally:
1601
+ if controller is not None:
1602
+ controller.restore_materials()
1603
+ try:
1604
+ env.close_env(clear_cache=True)
1605
+ except Exception:
1606
+ pass
1607
+ attempted_seeds.append(seed)
1608
+ attempts += 1
1609
+ session_attempts += 1
1610
+ write_collection_summary(summary_path, checkpoint_payload())
1611
+ write_standard_dataset_metadata(output_dir, summaries)
1612
+ time.sleep(0.2)
1613
+
1614
+ if successful != episodes:
1615
+ raise RuntimeError(
1616
+ f"Collected only {successful}/{episodes} successful episodes after {attempts} attempts"
1617
+ )
1618
+ return output_dir
1619
+
1620
+
1621
+ def parse_args() -> argparse.Namespace:
1622
+ parser = argparse.ArgumentParser(description=__doc__)
1623
+ parser.add_argument(
1624
+ "--config",
1625
+ type=Path,
1626
+ default=REPO_ROOT / "task_config" / "demo_dynamicvla_follow.yml",
1627
+ )
1628
+ parser.add_argument(
1629
+ "--episodes",
1630
+ type=int,
1631
+ default=None,
1632
+ help="Target total episode count (defaults to episode_num in the config)",
1633
+ )
1634
+ parser.add_argument("--seed-start", type=int, default=0)
1635
+ parser.add_argument(
1636
+ "--resume",
1637
+ action="store_true",
1638
+ help="Resume a checkpointed dataset until --episodes total examples exist",
1639
+ )
1640
+ return parser.parse_args()
1641
+
1642
+
1643
+ def main() -> None:
1644
+ cli = parse_args()
1645
+ config = load_config(cli.config.resolve())
1646
+ episodes = int(cli.episodes if cli.episodes is not None else config["episode_num"])
1647
+ if episodes <= 0:
1648
+ raise ValueError("--episodes must be positive")
1649
+ output = collect(
1650
+ config,
1651
+ episodes=episodes,
1652
+ seed_start=cli.seed_start,
1653
+ resume=cli.resume,
1654
+ )
1655
+ print(f"\nGenerated {episodes} examples in {output}")
1656
+
1657
+
1658
+ if __name__ == "__main__":
1659
+ main()
provenance/demo_dynamicvla_follow_dataset.yml ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset-scale clean split for causal approach-follow-grasp demonstrations.
2
+ # The exact merged-dataset episode/source mapping and all historical collection
3
+ # phases are recorded in the final summary.json. The seed prefix below records
4
+ # the attempts made in the original formal shard and remains useful for resume
5
+ # compatibility; new expansion runs use the harder distribution below.
6
+ # New entries first run a three-example high-speed pilot on known-stable scenes,
7
+ # then cover previously unused clean-level1 seeds before falling back to fresh
8
+ # integer seeds. Motion parameters remain different even when a scene seed is
9
+ # deliberately reused for a controller-limit check.
10
+ render_freq: 0
11
+ # CUDA_VISIBLE_DEVICES selects the physical GPU; inside the process it is cuda:0.
12
+ render_device: cuda:0
13
+ episode_num: 50
14
+ seed_start: 0
15
+ seed_list: [1, 15, 23, 5, 6, 36, 40, 7, 10, 43, 45, 17, 13, 48, 61, 24, 21, 53, 70, 44, 37, 60, 79, 62, 39, 69, 86, 68, 42, 74, 87, 85, 47, 77, 94, 83, 96, 105, 15, 7, 48, 105, 40, 83, 92, 65, 67, 71, 84, 100, 102, 103, 88, 51, 90, 58]
16
+ # High-speed online following is intentionally harder than the original
17
+ # precomputed-intercept demonstrations, so leave enough attempts for strict
18
+ # rejection instead of weakening the quality gate.
19
+ max_attempts: 200
20
+ save_freq: 8
21
+ embodiment: [aloha-agilex]
22
+ planner_backend: curobo
23
+ # Match the standard training splits: generate 100 seen and 100 unseen
24
+ # language variants per accepted scene after collection/finalization.
25
+ language_num: 100
26
+
27
+ # Match the old clean split first. Visual randomization will be collected as
28
+ # a separate split so appearance shift is not entangled with motion coverage.
29
+ domain_randomization:
30
+ random_background: false
31
+ cluttered_table: false
32
+ clean_background_rate: 1
33
+ random_head_camera_dis: 0
34
+ random_table_height: 0
35
+ random_light: false
36
+ crazy_random_light_rate: 0
37
+
38
+ camera:
39
+ head_camera_type: D435
40
+ wrist_camera_type: D435
41
+ collect_head_camera: true
42
+ collect_wrist_camera: true
43
+
44
+ data_type:
45
+ rgb: true
46
+ third_view: false
47
+ depth: false
48
+ pointcloud: false
49
+ observer: false
50
+ endpose: true
51
+ qpos: true
52
+ mesh_segmentation: false
53
+ actor_segmentation: false
54
+
55
+ pcd_down_sample_num: 1024
56
+ pcd_crop: true
57
+ save_path: data
58
+ clear_cache_freq: 1
59
+ collect_data: true
60
+ eval_video_log: true
61
+
62
+ dynamic_follow:
63
+ controller_mode: smooth_joint_servo
64
+ # These values are replaced episode-by-episode by the distribution below.
65
+ speed_x: 0.075
66
+ speed_y: 0.0
67
+ offscreen_start_x: 0.56
68
+ object_only_seconds: 1.45
69
+ prediction_horizon_seconds: 0.23
70
+ replanning_horizon_steps: 40
71
+ medium_horizon_steps: 80
72
+ catchup_horizon_steps: 160
73
+ frame_stride_steps: 8
74
+ pre_grasp_distance: 0.10
75
+ approach_tolerance: 0.025
76
+ grasp_tolerance: 0.018
77
+ follow_hold_seconds: 0.60
78
+ close_seconds: 0.90
79
+ release_fraction: 0.85
80
+ # Match the original adjust_bottle demonstration's 10-cm withdrawal.
81
+ lift_height: 0.10
82
+ settle_seconds: 0.40
83
+ max_approach_cycles: 35
84
+ max_descend_cycles: 24
85
+ velocity_ema: 0.65
86
+ servo_replan_steps: 50
87
+ servo_position_gain: 5.0
88
+ servo_max_joint_velocity: 1.4
89
+ servo_max_joint_acceleration: 3.0
90
+ servo_max_position_lead: 0.08
91
+ complete_original_task: true
92
+ # Allow one extra second for near-converged placements; the controller exits
93
+ # early as soon as the unchanged position/orientation tolerances are met.
94
+ place_max_seconds: 5.5
95
+ # The repository's task check only requires a clearly correct side/upright
96
+ # placement. A 25-mm metric gate remains strict visually without rejecting
97
+ # otherwise successful demonstrations for millimetre-scale servo residuals.
98
+ place_position_tolerance: 0.025
99
+ # Keep the online servo's early-stop criterion tighter than the final
100
+ # object-level quality gate above.
101
+ place_control_position_tolerance: 0.015
102
+ place_orientation_tolerance_degrees: 3.0
103
+ upright_axis_tolerance_degrees: 12.0
104
+ place_max_joint_velocity: 0.8
105
+ place_max_joint_acceleration: 1.2
106
+ # Match the original dynamic adjust_bottle contact physics during carrying.
107
+ object_mass_kg: 0.01
108
+ held_linear_damping: 10.0
109
+ held_angular_damping: 10.0
110
+ grasp_settle_seconds: 0.25
111
+ # Created only after both physical fingers contact the bottle. It preserves
112
+ # that measured relative pose and never snaps to a computed future pose.
113
+ stabilize_grasp_with_drive: true
114
+ grasp_drive_stiffness: 100000.0
115
+ grasp_drive_damping: 1000.0
116
+ grasp_drive_force_limit: 1000000.0
117
+ grasp_drive_limit_epsilon: 0.000001
118
+
119
+ dynamic_follow_distribution:
120
+ enabled: true
121
+ schedule_size: 50
122
+ # The finalized 50-example split retains a small slow tail for coverage but
123
+ # has mean/median 0.0964/0.1010 m/s and 34/50 examples at >=0.10 m/s (versus
124
+ # 0.0479 m/s mean in the old clean split). Further collection deliberately
125
+ # stays in this validated high-speed band; 0.12+ m/s online-follow pilots
126
+ # were too failure-prone to be useful production data.
127
+ speed_mean: 0.105
128
+ speed_sigma: 0.004
129
+ speed_min: 0.10
130
+ speed_max: 0.11
131
+ entry_angle_max_degrees: 8.0
132
+ offscreen_start_min: 0.56
133
+ offscreen_start_max: 0.60
134
+ action_start_abs_x_min: 0.44
135
+ action_start_abs_x_max: 0.47
136
+ follow_hold_min: 0.50
137
+ follow_hold_max: 0.70