Add sanitized iUMI inference and robot deployment source
Browse filesBilingual documentation; Flexiv deployment bridge; FLUX and OpenPI backends; Python 3.12 OpenPI configuration. Source-only release without weights, recordings or credentials.
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +24 -0
- LICENSE +201 -0
- LICENSES.md +12 -0
- README.md +76 -0
- checksums.sha256 +307 -0
- configs/inference.env.example +24 -0
- docs/CHECKPOINTS_FLUX.md +38 -0
- docs/CHECKPOINTS_PI05.md +48 -0
- docs/INFERENCE_CONTRACT.md +16 -0
- docs/VALIDATION.md +3 -0
- docs/validation.json +18 -0
- flexiv-umi-infer/.gitignore +10 -0
- flexiv-umi-infer/LICENSE +201 -0
- flexiv-umi-infer/README.md +308 -0
- flexiv-umi-infer/configs/anchor.example.json +7 -0
- flexiv-umi-infer/configs/cell.env.example +26 -0
- flexiv-umi-infer/data/.gitkeep +0 -0
- flexiv-umi-infer/pyproject.toml +24 -0
- flexiv-umi-infer/tests/__init__.py +0 -0
- flexiv-umi-infer/tests/conftest.py +6 -0
- flexiv-umi-infer/tests/test_cloth_defaults.py +17 -0
- flexiv-umi-infer/tests/test_flexiv_trace.py +165 -0
- flexiv-umi-infer/tests/test_flux_action_dual.py +278 -0
- flexiv-umi-infer/tests/test_rollout_rec.py +139 -0
- flexiv-umi-infer/tools/README.md +57 -0
- flexiv-umi-infer/tools/insta360_cli_dual.cc +482 -0
- flexiv-umi-infer/umi_infer/__init__.py +0 -0
- flexiv-umi-infer/umi_infer/check_cam.py +180 -0
- flexiv-umi-infer/umi_infer/codec/__init__.py +0 -0
- flexiv-umi-infer/umi_infer/codec/umi_decode.py +199 -0
- flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py +472 -0
- flexiv-umi-infer/umi_infer/codec/umi_spline.py +94 -0
- flexiv-umi-infer/umi_infer/config.py +47 -0
- flexiv-umi-infer/umi_infer/export_E.py +74 -0
- flexiv-umi-infer/umi_infer/policies/__init__.py +0 -0
- flexiv-umi-infer/umi_infer/policies/base.py +24 -0
- flexiv-umi-infer/umi_infer/policies/flux_action_dual.py +350 -0
- flexiv-umi-infer/umi_infer/policies/mock.py +128 -0
- flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py +373 -0
- flexiv-umi-infer/umi_infer/policy_server.py +226 -0
- flexiv-umi-infer/umi_infer/protocol.py +228 -0
- flexiv-umi-infer/umi_infer/robot_agent.py +232 -0
- flexiv-umi-infer/umi_infer/robot_io/__init__.py +0 -0
- flexiv-umi-infer/umi_infer/robot_io/base.py +37 -0
- flexiv-umi-infer/umi_infer/robot_io/cam_ids.py +29 -0
- flexiv-umi-infer/umi_infer/robot_io/flexiv.py +1567 -0
- flexiv-umi-infer/umi_infer/robot_io/gripper_can.py +323 -0
- flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py +647 -0
- flexiv-umi-infer/umi_infer/robot_io/insta_live.py +350 -0
- flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py +225 -0
.gitignore
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Local environments and caches
|
| 2 |
+
.venv/
|
| 3 |
+
**/__pycache__/
|
| 4 |
+
.pytest_cache/
|
| 5 |
+
.runtime/
|
| 6 |
+
.cache/
|
| 7 |
+
# OS metadata
|
| 8 |
+
.DS_Store
|
| 9 |
+
**/.DS_Store
|
| 10 |
+
__MACOSX/
|
| 11 |
+
**/._*
|
| 12 |
+
# Private site settings and runtime recordings
|
| 13 |
+
.env
|
| 14 |
+
.env.*
|
| 15 |
+
*.env
|
| 16 |
+
cell.env
|
| 17 |
+
/data/
|
| 18 |
+
/recordings/
|
| 19 |
+
/logs/
|
| 20 |
+
# External model assets
|
| 21 |
+
*.safetensors
|
| 22 |
+
*.ckpt
|
| 23 |
+
*.pt
|
| 24 |
+
*.pth
|
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.
|
LICENSES.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 许可证 / Licenses
|
| 2 |
+
|
| 3 |
+
| 组件 / Component | 源码许可 / Source license | 文件 / File |
|
| 4 |
+
| --- | --- | --- |
|
| 5 |
+
| Flexiv UMI inference | Apache-2.0 | [LICENSE](flexiv-umi-infer/LICENSE) |
|
| 6 |
+
| FLUX UMI | Apache-2.0 | [LICENSE](flux-umi/LICENSE), [NOTICE](flux-umi/NOTICE) |
|
| 7 |
+
| OpenPI UMI | Apache-2.0 | [LICENSE](openpi-umi/LICENSE) |
|
| 8 |
+
| Gemma terms | Gemma Terms of Use | [LICENSE_GEMMA.txt](openpi-umi/LICENSE_GEMMA.txt) |
|
| 9 |
+
|
| 10 |
+
模型权重、编码器和厂商SDK需另行准备,并遵循各自许可。
|
| 11 |
+
|
| 12 |
+
Model weights, encoders and vendor SDKs are configured separately and retain their respective licenses.
|
README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
- zh
|
| 6 |
+
tags:
|
| 7 |
+
- robotics
|
| 8 |
+
- umi
|
| 9 |
+
- bimanual
|
| 10 |
+
- openpi
|
| 11 |
+
- flux
|
| 12 |
+
- inference
|
| 13 |
---
|
| 14 |
+
|
| 15 |
+
# 中文 / English
|
| 16 |
+
|
| 17 |
+
[中文](#zh) · [English](#en)
|
| 18 |
+
|
| 19 |
+
<a id="zh"></a>
|
| 20 |
+
|
| 21 |
+
# iUMI Inference · 双臂UMI推理与部署
|
| 22 |
+
|
| 23 |
+
Crobotia iUMI的模型推理与机器人部署代码,支持OpenPI(π0.5)和FLUX后端,包含配置模板、启动脚本及双臂名义URDF。
|
| 24 |
+
|
| 25 |
+
## 获取代码
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
git clone https://huggingface.co/Crobotia/iUMI_Inference
|
| 29 |
+
cd iUMI_Inference
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
| 目录 | 内容 |
|
| 33 |
+
| --- | --- |
|
| 34 |
+
| flexiv-umi-infer/ | 策略服务、机器人/相机/夹爪接口及数据记录 |
|
| 35 |
+
| flux-umi/ | FLUX模型与UMI数据表示 |
|
| 36 |
+
| openpi-umi/ | OpenPI模型、数据变换与客户端 |
|
| 37 |
+
| scripts/ | 模型服务和机器人端启动脚本 |
|
| 38 |
+
| configs/ | 推理配置模板 |
|
| 39 |
+
|
| 40 |
+
OpenPI使用Linux(glibc ≥2.31);按`openpi-umi/.python-version`配置Python3.12,在该目录运行`uv sync --frozen --python 3.12`。
|
| 41 |
+
|
| 42 |
+
FLUX使用`scripts/run_flux_server.sh`,OpenPI使用`scripts/run_pi05_server.sh`,机器人端使用`scripts/run_robot.sh`。两类模型使用独立环境,按各子项目说明安装依赖。启动前配置模型资源路径及设备标定;机器人脚本默认为dry run。
|
| 43 |
+
|
| 44 |
+
运行前准备模型权重、所需编码器、厂商SDK及设备标定。输入输出约定见`docs/INFERENCE_CONTRACT.md`,安装与设备配置见各子项目README。
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
<a id="en"></a>
|
| 49 |
+
|
| 50 |
+
# iUMI Inference · Bimanual UMI Inference and Deployment
|
| 51 |
+
|
| 52 |
+
Model inference and robot deployment code for Crobotia iUMI, with OpenPI (π0.5) and FLUX backends, configuration templates, launch scripts and a nominal dual-arm URDF.
|
| 53 |
+
|
| 54 |
+
## Get the code
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
git clone https://huggingface.co/Crobotia/iUMI_Inference
|
| 58 |
+
cd iUMI_Inference
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
| Directory | Purpose |
|
| 62 |
+
| --- | --- |
|
| 63 |
+
| flexiv-umi-infer/ | Policy service, robot/camera/gripper interfaces and recording |
|
| 64 |
+
| flux-umi/ | FLUX models and UMI representation |
|
| 65 |
+
| openpi-umi/ | OpenPI models, data transforms and client |
|
| 66 |
+
| scripts/ | Policy-server and robot-agent launchers |
|
| 67 |
+
| configs/ | Inference configuration templates |
|
| 68 |
+
|
| 69 |
+
For OpenPI, use Linux (glibc ≥2.31) and Python 3.12 as pinned in `openpi-umi/.python-version` and run `uv sync --frozen --python 3.12` from that directory.
|
| 70 |
+
|
| 71 |
+
Launch FLUX with `scripts/run_flux_server.sh`, OpenPI with `scripts/run_pi05_server.sh`, and the robot agent with `scripts/run_robot.sh`. Use separate environments for the model backends and follow each project's dependency instructions. Configure model resource paths and cell calibration before launch. The robot script defaults to dry run.
|
| 72 |
+
|
| 73 |
+
Before running, prepare model weights, required encoders, vendor SDKs and cell calibration. See `docs/INFERENCE_CONTRACT.md` for input/output conventions and the subproject READMEs for installation and device configuration.
|
| 74 |
+
|
| 75 |
+
## 许可证 / License
|
| 76 |
+
|
| 77 |
+
源码采用Apache-2.0许可,各子项目保留原有声明;Gemma、模型资源及厂商SDK遵循各自条款。详见[LICENSES.md](LICENSES.md)。
|
| 78 |
+
|
| 79 |
+
Source code is licensed under Apache-2.0, with upstream notices retained in each component. Gemma, model resources and vendor SDKs retain their respective terms. See [LICENSES.md](LICENSES.md).
|
checksums.sha256
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
6b9d5bb0a11b8f11de5274ae0168adcb26bb4a9a92ce2785cb9d9fb81eb62742 .gitignore
|
| 2 |
+
c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 LICENSE
|
| 3 |
+
14239d1e7b350d922e247861520079c99b2f3bf572154af74890b85bc25ea65c LICENSES.md
|
| 4 |
+
b8074f763f8e1d8b20ec809d315e67123a53bfd458e89f973f8993880f246bdb README.md
|
| 5 |
+
60e7b1fa5876ac5074cda70fd52fa03814352f8be4fbc0b49eabe8f549325f32 configs/inference.env.example
|
| 6 |
+
7fe74fe0ec4ece29718a69ab686be6693157b9b4b7356bff9c5c1498fb8f742b docs/CHECKPOINTS_FLUX.md
|
| 7 |
+
ecaf5b17769bc593d53b5170d857902ba39db840baff1ccfb358f056cd2a5b6f docs/CHECKPOINTS_PI05.md
|
| 8 |
+
8aedc1e1c6cb6531b5fdc825a9e89421457542b6bb951f6ebf35cbd4a5fa2266 docs/INFERENCE_CONTRACT.md
|
| 9 |
+
118ba0b007d38dbca6b458de432977b8ddfd8ac80689056b59aaba0ede857457 docs/VALIDATION.md
|
| 10 |
+
9526e276e76a8991c508eb44303eb2c70a32820d05ab1edd158c03c70e77d89b docs/validation.json
|
| 11 |
+
42eee4254f5c858d4b8394e089c755c5593fa245004a3f3bc3790adcb2b64d3e flexiv-umi-infer/.gitignore
|
| 12 |
+
c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 flexiv-umi-infer/LICENSE
|
| 13 |
+
b10b1431edc043376db249fe9670d8add3dce5accd4cc417a2ab596a5b655a8b flexiv-umi-infer/README.md
|
| 14 |
+
80183544c5e1e0989543cd8890c718744ac2ef80372638768c08747a4c53ed44 flexiv-umi-infer/configs/anchor.example.json
|
| 15 |
+
c660c0c97fc00fd18826fb476752f66c4b9f0ed28a1e837c58c4101f28887ee4 flexiv-umi-infer/configs/cell.env.example
|
| 16 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/data/.gitkeep
|
| 17 |
+
841aac6628213fd95738357123dc35d0ec284f5b019c13b753d4569b990699e8 flexiv-umi-infer/pyproject.toml
|
| 18 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/tests/__init__.py
|
| 19 |
+
16fa68ba18ded9fc02ce0ea4683d59b304bce8f3a306da9b7646c9cc624ea2ab flexiv-umi-infer/tests/conftest.py
|
| 20 |
+
8f4ada186a728752e46b1c685213c8abe2a0631f0e87f57cfd9c20b297be301d flexiv-umi-infer/tests/test_cloth_defaults.py
|
| 21 |
+
2afd295bbed79e36b59cc9affbb9c77ba6793916adfc8b21b6363c07c10aef4b flexiv-umi-infer/tests/test_flexiv_trace.py
|
| 22 |
+
3e682defbaa40a0476ed5d1919cd96b0538e2a89584091bad984bca94329c642 flexiv-umi-infer/tests/test_flux_action_dual.py
|
| 23 |
+
03b742081d40c132b11bb838b56d3cd12d37aa1440954d290ac0ed5c5a5b3798 flexiv-umi-infer/tests/test_rollout_rec.py
|
| 24 |
+
af575d5a0a1473936a4f886fa1466465bb1b694b51bf009182295d03f9bf4b71 flexiv-umi-infer/tools/README.md
|
| 25 |
+
92a07fbe0962ac7d93d54576968e8f7baf4d249597aba2d5f8634b822651d061 flexiv-umi-infer/tools/insta360_cli_dual.cc
|
| 26 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/__init__.py
|
| 27 |
+
58423863c5a932691a10c32a2047462777e87882c42771d87d7001b3582d0cde flexiv-umi-infer/umi_infer/check_cam.py
|
| 28 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/codec/__init__.py
|
| 29 |
+
3c483daaabc2688f6c81616ca9bf6cdcf5a5f425429b348a5f83e30530fa5642 flexiv-umi-infer/umi_infer/codec/umi_decode.py
|
| 30 |
+
82ef7d599f403d6104c77bdcd5f015ed7a7cee215d9ed204d0c9fb1983354b49 flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py
|
| 31 |
+
0897f80a731cdcc71914eef3bfe806a9bfbabe18f6bf60d587bef6fcd04a23c9 flexiv-umi-infer/umi_infer/codec/umi_spline.py
|
| 32 |
+
3be9b7e5a74f2c1de805a0574710967cecebdd55aa0850fb8a31933dd0673b97 flexiv-umi-infer/umi_infer/config.py
|
| 33 |
+
82e5485459cac03989d7799676df5fafa9f06b19ed99d3c13142784721e2e2f6 flexiv-umi-infer/umi_infer/export_E.py
|
| 34 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/policies/__init__.py
|
| 35 |
+
0c3c35af3126ea2716484ce6e0a5852d49021dd7fe32d04e7960e5e23eb14eb4 flexiv-umi-infer/umi_infer/policies/base.py
|
| 36 |
+
1688a89dd2d291c9350ae700e88ab28d97f0623c0de1dec205693f88f8c4200d flexiv-umi-infer/umi_infer/policies/flux_action_dual.py
|
| 37 |
+
06b2f047a719623dc9b83fac3b690c006e6fa89e3afcea9b619635353dfd0263 flexiv-umi-infer/umi_infer/policies/mock.py
|
| 38 |
+
e0cdbb82653cc0fe7d5a9cbdce99422dd665b307e84eb9c3d406608f1c654a7d flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py
|
| 39 |
+
da2e71e8410be9bb734716eaf8b55a24a4ae86229359e6c941f22228e157ad2f flexiv-umi-infer/umi_infer/policy_server.py
|
| 40 |
+
79eff4d235eb5fe03f2bcf1e731a0b79614dec76d9faf02e8dfd159267d6168e flexiv-umi-infer/umi_infer/protocol.py
|
| 41 |
+
0517326eae9d98e77fd37741b9b69c8298af257042ee433806a260ed99a6c090 flexiv-umi-infer/umi_infer/robot_agent.py
|
| 42 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/robot_io/__init__.py
|
| 43 |
+
c2a3a19b09a7d507e79142748c45979c41a8e07d49219ce6b05ebb1fcc6a49b1 flexiv-umi-infer/umi_infer/robot_io/base.py
|
| 44 |
+
5bc074b735e533d16f9a301b8019dfd2ed09143a2eeeb5af4e493c64cf2fea3d flexiv-umi-infer/umi_infer/robot_io/cam_ids.py
|
| 45 |
+
effc2e2a3740f74b982408ab4a578fa5c08dd00019d2a2dea6572344c2231baf flexiv-umi-infer/umi_infer/robot_io/flexiv.py
|
| 46 |
+
70f9f69e495e978cd010518b43cffe838e05c8b9768dbbc3323f45aeabf1cd4a flexiv-umi-infer/umi_infer/robot_io/gripper_can.py
|
| 47 |
+
c6fdd15f60481270c6208a9b7e428f85315a6273865308a84cd829303cb5ad88 flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py
|
| 48 |
+
7438aa26f6ae5ad5e866d741abc0b1cbe588092e499d4ae081bb4482fb57d9ba flexiv-umi-infer/umi_infer/robot_io/insta_live.py
|
| 49 |
+
1b48a111a668ac06ca641b0462b1568130906555d9823b353931dc46f01da598 flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py
|
| 50 |
+
4cb45a18fde7e181223bfb91d4afc44a5279c2bcd577ef703fb3c7a1c975d9e2 flexiv-umi-infer/umi_infer/robot_io/mock.py
|
| 51 |
+
d995f56cb8b535a82ffc5a7df7f31e62782e24c55c8db02139ee3409b08d2c18 flexiv-umi-infer/umi_infer/robot_io/pose_math.py
|
| 52 |
+
5cd362467442c368baad7412166b51d1ac57dc714dc5535e1aca8484c39df551 flexiv-umi-infer/umi_infer/robot_io/rollout_rec.py
|
| 53 |
+
6d05cf21d13cf85ad7fcede2fb4eb615052d616341f1065b59caf41f9a749398 flexiv-umi-infer/urdf/flexiv_rizon4_dual_umi.urdf
|
| 54 |
+
94795a39dbf0403579cb3b520eb32b17da77cf7a18f96a70897a4bd7269eca3a flux-umi/.github/workflows/cpu.yml
|
| 55 |
+
d63b857a6ffdd4a439699799d055011cb326dd6a8153cbfca7d9f08e3dea963f flux-umi/.gitignore
|
| 56 |
+
c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 flux-umi/LICENSE
|
| 57 |
+
583bba0e76b647a973d86854f8af7b983c4bbc29dae239e22da1e0288efb9b61 flux-umi/NOTICE
|
| 58 |
+
7f0e9239598e3c48b42f276f2dc7945fd0fb309eb2585ddda5c94b7b6ece8ef7 flux-umi/README.md
|
| 59 |
+
c39d803c7a1485b12f4e14f535858d5c5c27e4e757484b140e7858ba93587cd9 flux-umi/configs/droid/public_sample.lock.json
|
| 60 |
+
3f98670de9e60f8b19f0a712e24be69b04f5161e569ae08f6adac66fe3ecd4bc flux-umi/configs/droid/train.json
|
| 61 |
+
a77bd3fbf83c99fc0739d0541006080809ea62af65f125f672860bcf56a60e91 flux-umi/configs/games/train.json
|
| 62 |
+
9ce066fa24a42a24407de232892e948b3c307a239ef2ba2b9ce8f0de66221fdf flux-umi/configs/so101/community_corpus.json
|
| 63 |
+
73c1bcdb3b9ecd5448a26d0d1bbd21b9eef4668fcbc0766e09543ff1a48e395b flux-umi/configs/so101/train.json
|
| 64 |
+
20a357bb2c45c64f792a5e089999d67616aaa4009d7303b8226c14d9518fbe0f flux-umi/configs/umi/umi_posttrain_16g.json
|
| 65 |
+
85caaee496298274765d4871cd3a6c910fc0d39fdfa40cd371d4c7225ac54cd9 flux-umi/docs/embodiments.md
|
| 66 |
+
7fe74fe0ec4ece29718a69ab686be6693157b9b4b7356bff9c5c1498fb8f742b flux-umi/docs/folding-checkpoint.md
|
| 67 |
+
04c31dd1d5cddc271f49c2ac58a2df1fcaf45bda6618535d483cae830b0c2b37 flux-umi/docs/setup.md
|
| 68 |
+
c827725c899f6ca3a90f771acd4c77e096b552e8619c9574b08e8ab77f10b86b flux-umi/docs/training-environment.md
|
| 69 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/examples/__init__.py
|
| 70 |
+
475dd51707eef76d456694d6a3ee3f04f93cba894db87e00c2ec98966eea0b53 flux-umi/examples/games/README.md
|
| 71 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/examples/games/__init__.py
|
| 72 |
+
8f03a3b2121a4c858386e2485f7ff7205ee9ca9813ce705864cb5b7bb278880c flux-umi/examples/games/dataset.py
|
| 73 |
+
3790c03edcf680dd24f43bbdb1cd74dd03a2c20ac5ae6c1494f40caee2d1fbb7 flux-umi/examples/games/test_trainer_games.py
|
| 74 |
+
3a1acee06057729348accfdc709c5702a23605f70f74260a7dbdc1ee40f0db07 flux-umi/pyproject.toml
|
| 75 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/__init__.py
|
| 76 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/checkpoints/__init__.py
|
| 77 |
+
db0c3018885375a6edf989a5d31fb5c227a46960a7a35ba1cb69c976cc96fd60 flux-umi/src/flux_action/checkpoints/artifacts.py
|
| 78 |
+
80d3aea6cebc03be04b17893e03bf124318dc42908e5a5f786c859cba4eac8e1 flux-umi/src/flux_action/cli.py
|
| 79 |
+
4a35842b6d27852f3b70920c863c3258c82dc266891c5690d15a2731f75f3353 flux-umi/src/flux_action/config.py
|
| 80 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/data/__init__.py
|
| 81 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/data/droid/__init__.py
|
| 82 |
+
e250e91835e875165db883432ce70bea20383a60be69d1ba5af4f9b7a1722bfe flux-umi/src/flux_action/data/droid/cosmos.py
|
| 83 |
+
2743077fb20902916fdbc1e22114a151d6948506bd410c78373f2cd47e9ae3c1 flux-umi/src/flux_action/data/droid/episodes.py
|
| 84 |
+
9ceea7ae053591580bc54fece2d4be08e3901711994058ec04ad8fe39a3d6fdb flux-umi/src/flux_action/data/droid/index.py
|
| 85 |
+
467d2d45cbabe5b7be3e1ce093a8cdadcebdeca7a58fbfb0fcc4f78528844d68 flux-umi/src/flux_action/data/droid/video.py
|
| 86 |
+
1efbe639cf11f4aa1a645c5d9e04cc50339df45ed9833f9108a3add12181d61e flux-umi/src/flux_action/data/lerobot/__init__.py
|
| 87 |
+
cb23610fd2fa05e0409b1692a116c3b88c91e998a8c2e43c7922ccd69a5a5f31 flux-umi/src/flux_action/data/lerobot/index.py
|
| 88 |
+
73f8f63e827c72ba71bb5c23477d57e261ccd841d365987853c5542447cd80c1 flux-umi/src/flux_action/data/schema.py
|
| 89 |
+
d002e5ce430c1a610d01b499a3736fb07b2d6ebd93ebd5abe804cfc1d88caa65 flux-umi/src/flux_action/data/umi/__init__.py
|
| 90 |
+
58579872786bc383fa45884e8319741d22317095effb7943935e05a47bfc3503 flux-umi/src/flux_action/data/umi/all_windows.py
|
| 91 |
+
036d6af65e697822c4720eb38bb04abf5ba150b7f9d7846968fa04739634badb flux-umi/src/flux_action/data/umi/dataset.py
|
| 92 |
+
f6800fcac7d980846bac532741a6c38522cca5b0dcc284221e6b8cada5dd1dbd flux-umi/src/flux_action/data/umi/representation.py
|
| 93 |
+
2d7a4032a8da9c0944d2e5c0d4a1c077c0953ed4280c34a503f1fbf5cd16332c flux-umi/src/flux_action/data/windows.py
|
| 94 |
+
fd70af80e92ea4d4a32d479a0d6c42916beb0aa0e597665e5fb64e29dc70b04e flux-umi/src/flux_action/hub.py
|
| 95 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/inference/__init__.py
|
| 96 |
+
8dd300f3363f34cd1381cee30d8e64ba967e6a21cbcc98fe23e5438c3dd7bbfb flux-umi/src/flux_action/inference/evaluate.py
|
| 97 |
+
6391d17e89cb01c7e4be41938fc7a5347e2ba74f9dfbe31300b54f5d13888ac5 flux-umi/src/flux_action/inference/offline.py
|
| 98 |
+
cc20073e7c82221047ac7bc29d223b933fab569d211cf615b3d209e040d2de2b flux-umi/src/flux_action/inference/precision.py
|
| 99 |
+
93855fe06f89d55551ec7601342f4c7ee4bca40ff037648f04a1259e7a113613 flux-umi/src/flux_action/inference/sampling.py
|
| 100 |
+
2a4acc16b7840fdb9b842ad9d63657d62c0318cd0456d07ec1a2a91a5e36be67 flux-umi/src/flux_action/inference/so101.py
|
| 101 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/models/__init__.py
|
| 102 |
+
a479eb38ac8b23b889d9ff35597b694aab23a1be84bb64d8e1f38c6bfd551322 flux-umi/src/flux_action/models/cute_qknorm_hybrid.py
|
| 103 |
+
3f953df25e520b0d9c4dfb8c70e1f4a871a0e71a7086c77a5630e10538165b6a flux-umi/src/flux_action/models/cute_rmsnorm_kernel.py
|
| 104 |
+
1e2f93599c864c7200e4764d94a3718eb5ae9cacd6ed57b25abcb3ae7c980f10 flux-umi/src/flux_action/models/cute_rope.py
|
| 105 |
+
759ec807617ff5472cd501d2bd53f043aaa881b38e5e6d0da5bc581c28fcdb17 flux-umi/src/flux_action/models/cute_vae_rope_kernel.py
|
| 106 |
+
3d75a54345d2e600abafcc6df7ed6fc31bb88461b5213edd70306c62b622c88c flux-umi/src/flux_action/models/dit_cute_qknorm.py
|
| 107 |
+
35706af2eaec9fbb698f3dd70d86780a568a817f87455838df059bfce309a037 flux-umi/src/flux_action/models/dit_fanout_linear.py
|
| 108 |
+
5aa3858278a13b0792e6c426e7bcf64ac4ad0b89873e23a6b18c721e3bdba9ff flux-umi/src/flux_action/models/dit_mod_rows.py
|
| 109 |
+
43da24b19a0d91c0bf594cab7121767306ab87d95f3f62e3cd616716f999ab4e flux-umi/src/flux_action/models/dit_norm_mod_gate.py
|
| 110 |
+
67100afc68724051b27bd609aa16a506514239888de17d2b34b35844fbc2dfb0 flux-umi/src/flux_action/models/dit_out_stage.py
|
| 111 |
+
ee5429a56a4fd980984bc7b0b8f6083dbb3167df9986133e3863114c3d576212 flux-umi/src/flux_action/models/dit_qknorm_rope_fused.py
|
| 112 |
+
d934ec932e13f248c3ba4cf32af9918cf0aa49849817041eb92f9cf3aec6aaa4 flux-umi/src/flux_action/models/dit_qknorm_triton.py
|
| 113 |
+
3a9175d739257a8d2daa48e62bbc6abb9eb95bcef6a659803664b9b1ff82f058 flux-umi/src/flux_action/models/dit_rope_triton.py
|
| 114 |
+
57b5e0f507d223b06d098873741b2c7e3d0bf155c2db31d199f9b2011abb235a flux-umi/src/flux_action/models/dit_swiglu_fused.py
|
| 115 |
+
b972c2da876ce30af417ced99eac45e24e5f7a30373fb771e079070ec1f33cb5 flux-umi/src/flux_action/models/dit_time_embed_dedup.py
|
| 116 |
+
c24b02a9d188a3eaafcb1dc89de551433a4d7269e11dae5af4248be246a16fe0 flux-umi/src/flux_action/models/positional.py
|
| 117 |
+
de51616e5a3c22d9852d6ca17440b9b7db8e0dda22c52b79600406b3404bf948 flux-umi/src/flux_action/models/runtime.py
|
| 118 |
+
0b0f736c8b5b92c4354a4733f0d9aef885d871e0057aa7650dcb76b9c4ce6b36 flux-umi/src/flux_action/models/swiglu_native_out.py
|
| 119 |
+
b5643ec523f7fdd591da73a7ff4d82fab96483c4ffc1c0e417a48649450a8dac flux-umi/src/flux_action/models/swiglu_native_out_adapter.py
|
| 120 |
+
fb76e4cbb8654c6007c4c9a8dc43abfb623dc164d85bbc285b79d522cb851063 flux-umi/src/flux_action/models/text_encoder.py
|
| 121 |
+
8c36a9fd8e9f1bead55ed0283238fbe6f206b24967fb5d5c2c6ee7baa3062d3d flux-umi/src/flux_action/models/transformer.py
|
| 122 |
+
a0f737d097901c58fd88162699328ec6b44b0a05ba54f71dc1d971725ca30ecd flux-umi/src/flux_action/models/transformer_inf_bf16.py
|
| 123 |
+
130ddd62b5b5ee4f908a3f84eee035e8f2aad37e85c976e846199986b2043548 flux-umi/src/flux_action/models/transformer_inf_fp8r.py
|
| 124 |
+
393f2d646d52923eabb23559ce9788d4434e177de770fd464786119bb2c2e06e flux-umi/src/flux_action/models/vae_cute_rmsnorm.py
|
| 125 |
+
a2057ea6a88d17dce2a2ca15d068aca3ad5c2f4132ee35623b6ff9489911fd45 flux-umi/src/flux_action/models/vae_cute_rope.py
|
| 126 |
+
7b5835ce3f3f096b9a052bd420e2a3ad0453d46894d619a6531e77ffdc01a0dd flux-umi/src/flux_action/models/vae_fused_gemm.py
|
| 127 |
+
5ce201e1482634fd00b14f5bb05310a08453423cf218cb29dc6b8ef03a48d3de flux-umi/src/flux_action/models/vae_fused_pointwise.py
|
| 128 |
+
2913a95b65f3ce75503c41601aa304ad4610eee95ba95c213b32003678960d61 flux-umi/src/flux_action/models/vae_graphed.py
|
| 129 |
+
02084a113dd0e13e0881d01f69815f6f55352f8bdf28e7989d25ab2a45e7011c flux-umi/src/flux_action/models/vae_ln_exact.py
|
| 130 |
+
4b4b00790103992513addd52950b513f1a1043a0145d11efb139164e4b0fbec8 flux-umi/src/flux_action/models/vae_merge_glue.py
|
| 131 |
+
1fdfaea257f47b13434326900a3b0463d0068e7bba40a25320ff48bf971e176d flux-umi/src/flux_action/models/vae_na3d_triton.py
|
| 132 |
+
f133d9c3ee3b3a01310f177bd16386f4738db79d427b7bdb624115e6e5350ab8 flux-umi/src/flux_action/models/vae_na3d_v2.py
|
| 133 |
+
c8c00d90e1ec6c4fc326c57751070ad1a3845ae4a087494db478bc8062d8da92 flux-umi/src/flux_action/models/vae_natten_no_lse.py
|
| 134 |
+
e6a8caa6f9af2ed8bbe225618d99566627917af27786f490293e3cc5b4de9f4d flux-umi/src/flux_action/models/vae_natten_tokperm.py
|
| 135 |
+
860a8a290b05f3dfa83a5972ddc8ef0c9b3d8d285ee38e23a495f95c4a44e38f flux-umi/src/flux_action/models/vae_qk_fused.py
|
| 136 |
+
ea71196f17d11c05f9b35778c13eea745497369f68f383f76c35b68b6e727d5e flux-umi/src/flux_action/models/video_vae.py
|
| 137 |
+
13aff43233302324336c0aadf73e97f210095adc133bdccf5e2cbbc4308d450f flux-umi/src/flux_action/models/wiring.py
|
| 138 |
+
aa0558daf2743d0c251fd2f433ed7a98cd54689057421ac74f96782f811155bc flux-umi/src/flux_action/policy.py
|
| 139 |
+
96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/processing/__init__.py
|
| 140 |
+
74fecbda8f05b453e694ec2457f6a8f35424a393e21aa42f135ba846dbb14362 flux-umi/src/flux_action/processing/batched_preprocess.py
|
| 141 |
+
cb6448d7de6b0fc0050f73237c6a6f864dd2c903881beece45b78f5ba2eea40d flux-umi/src/flux_action/processing/history.py
|
| 142 |
+
73ac9b89b5015c02d1c629fc1494cc4743ed2d1784e9c0d0a3285f85fb06f492 flux-umi/src/flux_action/processing/normalization.py
|
| 143 |
+
dc88b0129304a00e112d1f693695a42aa48eb85de6550d93f4584b80a558b513 flux-umi/src/flux_action/processing/packing.py
|
| 144 |
+
9821634dc48decda1111dbf1ac28ed6cb68aef7630c3c65aa93a4d51e207f827 flux-umi/src/flux_action/serving/__init__.py
|
| 145 |
+
d9c277e50262e000a46c9a131f334eed16a362f625c5b10e727d9a5919ea8896 flux-umi/src/flux_action/serving/protocol.py
|
| 146 |
+
f78eed26f8e292c8aeba5abadecba2327b2862ab6e583fd237483106fc04b2c4 flux-umi/src/flux_action/serving/robolab.py
|
| 147 |
+
0f9286a4ec247764c23cc33cc71bb861e9f0e870e366848966df874bab1e660c flux-umi/src/flux_action/training/__init__.py
|
| 148 |
+
e1d7ae9450ce01034a85b4c5c762f715f71859e3c5f6a4e3592a246b50616e89 flux-umi/src/flux_action/training/activation_offload.py
|
| 149 |
+
b027cf267a763da50263de7ddc584056872ae31d54d2866f9c1c7079f60c1e8a flux-umi/src/flux_action/training/checkpoint.py
|
| 150 |
+
3d11e924c18e5ebe2cb4b37df7ff02acea488f5536f3f0e74545d74e3a7e6b40 flux-umi/src/flux_action/training/data.py
|
| 151 |
+
7780780f7baa04ed5ce02cec7d9f7cec30275933b725a99d19d7b161a92ede6f flux-umi/src/flux_action/training/distributed.py
|
| 152 |
+
e31869e09e9b81d6ddd229f190bdd30efcbc26aa754e6d320c970a85dc2f9199 flux-umi/src/flux_action/training/ema.py
|
| 153 |
+
4fb5dbddcc3cba6faec091bf28532d2b89e7bf6dafb8909c3e562f00a79cff98 flux-umi/src/flux_action/training/schedule.py
|
| 154 |
+
935ed868abfd630aacc9a18a0d625b3a8c872bb81feaef7c61789549b1fdd478 flux-umi/src/flux_action/training/timing.py
|
| 155 |
+
1aed33cccd133ee9ad4b41ad47e1ceefc7b98e710092682c275a439b407f26ff flux-umi/src/flux_action/training/trainer.py
|
| 156 |
+
e1068092ab789c254812642439b35dfcb014ff2dcfe477efb25ce7b1e7f2f3b0 flux-umi/tests/conftest.py
|
| 157 |
+
d745251355b5e9b01b0b7561efef09dd4d969f81f039485bf75fc74cc614c568 flux-umi/tests/fixtures/so101_history/README.md
|
| 158 |
+
6870eaf267ebad5fc3f7dd6fd7147fa61e8126411166e0b0cc93b4bb7f56818c flux-umi/tests/fixtures/so101_history/config.json
|
| 159 |
+
becfefcda2c7116d31d83c8877b015d30dffaedbfce8fa2d854521b738b81d62 flux-umi/tests/fixtures/so101_history/policy_postprocessor.json
|
| 160 |
+
4c6fb125252845fe64258ce4cfac8d6f29297be77d285abf862f0b894b55ae76 flux-umi/tests/fixtures/so101_history/policy_preprocessor.json
|
| 161 |
+
622cf6eff6e33254bcb12d3b265411f16044b0dcfbdf10c7cab1c34014049cd6 flux-umi/tests/synthetic_droid.py
|
| 162 |
+
8bfb1259b8a1b57dfb46367733b3ffb52e464fa928c65f7124b412f53ed8b050 flux-umi/tests/synthetic_lerobot.py
|
| 163 |
+
c91fd843ab8a263734d9cebbffd6b611b18b97c83afb7b603e86765c5e20a76c flux-umi/tests/test_cameras.py
|
| 164 |
+
4e75d642efd6d921289652c99a4343609ff24d8c89e6ae2297d6f6823af24416 flux-umi/tests/test_cosmos.py
|
| 165 |
+
e38c9c061aab7bebe82e5f1bd57ab566c7c51d6ae034e47d6ea1e4b02b0ee1f7 flux-umi/tests/test_data.py
|
| 166 |
+
8ed736acec7e20f72d7fe0801071af21e4c86578c36a0b068086bab4c278d09f flux-umi/tests/test_droid_cli.py
|
| 167 |
+
9af867e8e3ce3a06e337883c75661fa3eb53d261c6d4756e8e37d9829ae1a8f8 flux-umi/tests/test_history_inference.py
|
| 168 |
+
eb70c02c0f6c90ef5a64493c658578ec2e2ce1303d7ec12898032d1c1c7144a4 flux-umi/tests/test_history_training.py
|
| 169 |
+
e4637f2d8076c559201f826cae48c0fedfe6a088a716a6778a348a7815d12a8e flux-umi/tests/test_hub.py
|
| 170 |
+
5b5d1128e4ccc19329dc2808df712f81f79eeef4748a2541033b73201978d8f2 flux-umi/tests/test_lerobot.py
|
| 171 |
+
13dbda4ce5d3bc49d4700926ed978035795abeae83418013e4fadf4f596d34b2 flux-umi/tests/test_offline.py
|
| 172 |
+
342e7397ad71c070ed58d55720ac10187ee6ad5cecb5e45130236feaff55736d flux-umi/tests/test_packed_windows.py
|
| 173 |
+
e55df90dd630985d7474b9bb7233c70e250e47ade9ff01e6484a974b0dc36001 flux-umi/tests/test_policy.py
|
| 174 |
+
64eab8c716530e6e92c486869867814dd9f8601e6e2f2f85f6643c3809b4acf1 flux-umi/tests/test_policy_optional_dependencies.py
|
| 175 |
+
3669e45970485e01acec311c0266086a3b4a029bcf8fcd586ea755c01a959ce4 flux-umi/tests/test_precision.py
|
| 176 |
+
06e6c466d990f444334691100cd89302cd5f4dcd51148c1e2ef2db752cec3210 flux-umi/tests/test_serving.py
|
| 177 |
+
976288b37a5050a030bf5c4ea13de17106e7cc37a9f42c8027d74f3439cd71d4 flux-umi/tests/test_shared_encoder_hub.py
|
| 178 |
+
3af3afbdf0a28c2be3cd859a878044a4319592941821402157a780a35c9531d7 flux-umi/tests/test_so101_config.py
|
| 179 |
+
6689cd91bc6c7bd15cfe1b7aed37de8bb6b1638c2fd2966450b4605eed031ecb flux-umi/tests/test_state_dropout.py
|
| 180 |
+
e438667accd30209006f4e235c6ec2d3af4bf104332dc1e4cf788b843cdddb9d flux-umi/tests/test_umi_epoch_stream.py
|
| 181 |
+
d714339a8c0564a7e17d42185ee5844b4b9b44029bfa3f9f41f1bd8a7f69fa0c flux-umi/tests/test_vae_training_prefix.py
|
| 182 |
+
0bc606326d4f17d96e4cacdcd0368528743cdff786bf49315c741ab11e80a28e flux-umi/tests/test_video.py
|
| 183 |
+
3d8311cea3965fb1764f1605328fa0ce5c0ecc48804bf2660747b59a0f61be6c flux-umi/tests/test_video_vae.py
|
| 184 |
+
396665643eb2a5a7369129e7769d67699e0812855fd695bada7621042c7ba86a flux-umi/tests/training/test_activation_offload.py
|
| 185 |
+
7ad190a394daae6ba8085005933a24e4dae340142c347b14312a2db5d5700c90 flux-umi/tests/training/test_batched_preprocess.py
|
| 186 |
+
87f887d4a09266af0679c111761840c675022bdf1a84b6914fa03aba9ef0622d flux-umi/tests/training/test_checkpoint.py
|
| 187 |
+
8c41a301d77906a3139b4221dbc334c3b722ef6d14a9217d00812537eef99cc0 flux-umi/tests/training/test_dit_fanout_linear.py
|
| 188 |
+
46b820c5b0d6d97c56f3a8a5ace818dab87bfe9039c847ba46106b8672f4c2d2 flux-umi/tests/training/test_dit_last_layer_rows.py
|
| 189 |
+
180c5fb4fd90c1cdd1ebd3a46fd25f5805ba4f39304b086b314610ce5a1cf84b flux-umi/tests/training/test_dit_mod_rows.py
|
| 190 |
+
942c81331915b5c4217b02d49d26b4003c0841d47135afc1b767d0bb11d613ba flux-umi/tests/training/test_dit_out_stage.py
|
| 191 |
+
82aac2ef0d0a3150fdd00722d9defb6cec1492e0c60468cc9adf100ce3549906 flux-umi/tests/training/test_dit_qknorm_rope_fused.py
|
| 192 |
+
b1b9781927c6d7166cbf97eaa4f8d1b49b9eac76ee434a7c23c11e4a92972d1f flux-umi/tests/training/test_dit_rows_fixes.py
|
| 193 |
+
329bc03e022bde95f44618d451d193c87f77695f3483d5ac0595fd883cd7808b flux-umi/tests/training/test_ema.py
|
| 194 |
+
c7e849db640ad0677ecc5dbb1b680f6ce93eb7dd1f647e9b210f20cb19c10a86 flux-umi/tests/training/test_embodiment_plug.py
|
| 195 |
+
71313d3e72bdb697e72a8cdc13e2cb738c37c63ae3b07d95596d9ce1831698e3 flux-umi/tests/training/test_pack_cache.py
|
| 196 |
+
751df4a73effff80bdb58942ccc940185249a54e196ec9a7285d97012a6bc1fc flux-umi/tests/training/test_perf2_options.py
|
| 197 |
+
ebab8e9b34a239be10f8079be095ca03f01790cd172d6c22d739be1a2dad79b9 flux-umi/tests/training/test_perf3_options.py
|
| 198 |
+
73ab34152145688f52c7079a0af1f5f95e51d601e5ac4a07686a6480d6c5e1ec flux-umi/tests/training/test_resume_prefetch_rng.py
|
| 199 |
+
99bd98c1a375fabf01a06481ab45da2616a787584add997826c3e2a46f56d3ae flux-umi/tests/training/test_schedule.py
|
| 200 |
+
079c7919a3debcac9bade3c2caa11585b33e3371e17ae29ee244a786a722f3c9 flux-umi/tests/training/test_trainer.py
|
| 201 |
+
c8ff99f7063c6a3dcc4e04f123386707bd705be776eb60ffb72ee59a6d16ca03 flux-umi/tests/training/test_vae_fused_gemm.py
|
| 202 |
+
2b483d559e5a82e320fd2d114f5ad4f4705a62c3ad070fe4644ad7d02917855d flux-umi/tests/training/test_vae_ln_exact.py
|
| 203 |
+
b19331fdf78702f0e82765cfc1fe046f1ee45a2d1dfac11199a55e96b6148bb7 flux-umi/tests/training/test_vae_merge_glue.py
|
| 204 |
+
de3282f5f097d0a81ba58c8bfc0c999173a8337a5008a41b318ae26c2bde1779 flux-umi/tests/training/test_vae_na3d_v2.py
|
| 205 |
+
3c0256e77d1cd1991b22fdadea124235b4e3d1fa40cdb7707a33bd25607d2500 flux-umi/tests/training/test_window_loader.py
|
| 206 |
+
0049930820d1dd6116108d0c8a5d09c216f87fe4c37db01d5e219da4ea571bce flux-umi/tools/prepare_umi_lerobot_v3.py
|
| 207 |
+
033f224839a39a259ccfd502a47116d0d659f31a5b93e5e581575c4f9fb2ece8 flux-umi/tools/train_umi.sh
|
| 208 |
+
8586969ff00e43b6c85606406ae6014ec79c10459df842967ab464e6a7373a09 flux-umi/uv.lock
|
| 209 |
+
10d44f6bfb4a32403a5cb7a279e7d0ccf39b2e9978214fb04584bded9b8a4945 openpi-umi/.github/workflows/pre-commit.yml
|
| 210 |
+
5ddee83abe84731df1896aad0bb931696b6b0f94ed5fa46251c4a42c6be2bbd5 openpi-umi/.github/workflows/test.yml
|
| 211 |
+
eae6f7ba5c007c6b2bc6848a9aca84475ce842c6692b5558cb8522f9b95dc2ba openpi-umi/.gitignore
|
| 212 |
+
5cb58628e068c3a25facd810095cb0e8f80ae7558d0a67ba197c01d9513baec5 openpi-umi/.pre-commit-config.yaml
|
| 213 |
+
7b55f8e67b5623c4bef3fa691288da9437d79d3aba156de48d481db32ac7d16d openpi-umi/.python-version
|
| 214 |
+
8da333112457fd84815551065bd3a3f80160054bbe89cc5794f57bfba2d50a89 openpi-umi/CONTRIBUTING.md
|
| 215 |
+
43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1 openpi-umi/LICENSE
|
| 216 |
+
3e2c24001f9ef57bf7ec959a3658fbb49cdad113cdf394c264da9d16f9bdd132 openpi-umi/LICENSE_GEMMA.txt
|
| 217 |
+
49001b2f146bbe97b5cad11898f44e904a7b2b4e4125c3d681842e3ac1094176 openpi-umi/README.md
|
| 218 |
+
ecaf5b17769bc593d53b5170d857902ba39db840baff1ccfb358f056cd2a5b6f openpi-umi/docs/folding-checkpoint.md
|
| 219 |
+
65ac9a3a555a2d3e78b75c9a4a446ad56e981842f81eaceef09e928e972adeab openpi-umi/docs/norm_stats.md
|
| 220 |
+
2146b043c6f92c618b44b81cf021d0352082211ebe250766918f32cc510f543c openpi-umi/examples/convert_jax_model_to_pytorch.py
|
| 221 |
+
00e8cb0e589d8f473588528f271f780fbe20cb67ba778e3e827d30cc3eb6cc92 openpi-umi/packages/openpi-client/pyproject.toml
|
| 222 |
+
91447944015cec709e8aa7655f7e9d64e1e4508e7023a57fe3746911c0fc6fed openpi-umi/packages/openpi-client/src/openpi_client/__init__.py
|
| 223 |
+
019b9d69cb26cc681331a2f95dbe60a2cc7b02d6d309c5d15b6457ab39798234 openpi-umi/packages/openpi-client/src/openpi_client/action_chunk_broker.py
|
| 224 |
+
88e98e0f06293f3c4767db675061664c4bba12f87242ba1e64377d1b8de8069e openpi-umi/packages/openpi-client/src/openpi_client/base_policy.py
|
| 225 |
+
d48b4bd7f44e79fe6db8a8e07c9161144fa250be686e1245014a8b47e6171977 openpi-umi/packages/openpi-client/src/openpi_client/image_tools.py
|
| 226 |
+
4df4b0ba0b95ba5e47160039c3e837a64d50c802b419a588211dffbaa732589c openpi-umi/packages/openpi-client/src/openpi_client/image_tools_test.py
|
| 227 |
+
c04568948fcee52b691e3be4b6cffb759f7e79ad67530fcd5d23095a0d13c057 openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy.py
|
| 228 |
+
2c6dd236720dae716d7bdf842b7d506a165e9563bf9d4376c95289269adcb973 openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py
|
| 229 |
+
b559885afd9645a91b9b6ee12a28513295474f987d11b16610fc0479dbe6de5b openpi-umi/packages/openpi-client/src/openpi_client/runtime/agent.py
|
| 230 |
+
c4d63952d1954bd4b72a3122223df36794812fea74cf1c7023433b5a90473c1c openpi-umi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py
|
| 231 |
+
1c12e5054b3401dec5f1f8b71eef0f625cb60e2b50784dcf19afa32c77107a7e openpi-umi/packages/openpi-client/src/openpi_client/runtime/environment.py
|
| 232 |
+
3daa242a9ce61ffb210789ef3ba6b1e3cade9de757fcd36af7b174c530345ea8 openpi-umi/packages/openpi-client/src/openpi_client/runtime/runtime.py
|
| 233 |
+
d269a2af8ec4056beb310e5c3c97d4468af01549c7ef80dd905652d8ac64f85b openpi-umi/packages/openpi-client/src/openpi_client/runtime/subscriber.py
|
| 234 |
+
36557cb0b91ccf31cd4fb4b508306850d76ed0feb4028dac5182d0f5a5d88005 openpi-umi/packages/openpi-client/src/openpi_client/websocket_client_policy.py
|
| 235 |
+
b115474a844299a32543792c9676d658ad2e9e4158ffc3d12d9a37e302f6bfc0 openpi-umi/pyproject.toml
|
| 236 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/scripts/__init__.py
|
| 237 |
+
61927c15848032db2d9bf10add57be9bdc4fab6268206dd43a87d05034066f36 openpi-umi/scripts/build_destatic_manifest.py
|
| 238 |
+
6573eb6c30bb645befe3b01771d19c9b7c37f244bbcb8bb4046328f2d5ddb8a6 openpi-umi/scripts/compute_norm_stats.py
|
| 239 |
+
90c2c413e31771b4ea5cb08441f083826974339ced66feb197c01ce041a4e288 openpi-umi/scripts/train_pytorch.py
|
| 240 |
+
b3d290c71400f17bb89edd0f2c82a4b8181868542eed6f3d3018d86ac0e0ba43 openpi-umi/scripts/train_umi_v3.sh
|
| 241 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/__init__.py
|
| 242 |
+
626672e385fb276396c119e2220421065c58f8ec602401e8bf2ae509f9fffaf3 openpi-umi/src/openpi/conftest.py
|
| 243 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/models/__init__.py
|
| 244 |
+
7e42ada4ae7e9995f0ef3e33a0c224758323c2015e2d9d72ec15726a8a001d2a openpi-umi/src/openpi/models/gemma.py
|
| 245 |
+
563c6e1ffd8afa31c406bcb8894a605e87df88f6c075d398d97a57af6bc3aefa openpi-umi/src/openpi/models/gemma_fast.py
|
| 246 |
+
ced28716950c34d84a1a6d0b03b1d9550000732721df884818080b6e78cb3289 openpi-umi/src/openpi/models/lora.py
|
| 247 |
+
a0f10525de7773310402b3ffa636e88ffff7035f3179b140aacc6809c122f085 openpi-umi/src/openpi/models/lora_test.py
|
| 248 |
+
0d74bc1d8f4623ac3d8e543710b8bf75f9b95e588a3ebf6127c659e001385cff openpi-umi/src/openpi/models/model.py
|
| 249 |
+
f8e71f195045d4e3ef1ddfafb2337fa52e5aa2f89bce1fde62f5cbfb67121f21 openpi-umi/src/openpi/models/model_test.py
|
| 250 |
+
24b32d7c6ed5e409459afa8ca5af96a4dae09c2dcdf48e828907e411f4f12342 openpi-umi/src/openpi/models/pi0.py
|
| 251 |
+
e15d71586f1a561b35c5651227607613fb16d2df411f3708b1c9d36b02544285 openpi-umi/src/openpi/models/pi0_config.py
|
| 252 |
+
627332a555046f2744ef144c45f8bd3361a9820cf68854a4528d0fdbba7e9aa3 openpi-umi/src/openpi/models/pi0_fast.py
|
| 253 |
+
5082873014a7fc45fb8414f517909e1c24cdafea980a1fb612e0aea6058ed0fe openpi-umi/src/openpi/models/pi0_test.py
|
| 254 |
+
14b4df0be280d5769fb0dc31a40cde27525dbb1980cc998c28475d62fa3cad32 openpi-umi/src/openpi/models/siglip.py
|
| 255 |
+
4eb8bd30360ebab22325e72ddad6f9ca192a87065f9ebda1239aaa953fd5acc5 openpi-umi/src/openpi/models/tokenizer.py
|
| 256 |
+
5abd179ce883420e39d4d18b33d0123290af752da243003aa48a3bc06dbb9517 openpi-umi/src/openpi/models/tokenizer_test.py
|
| 257 |
+
88866638ee4775f46a222561a957bd35e20600fe38c5888b587016ad77b1065f openpi-umi/src/openpi/models/utils/fsq_tokenizer.py
|
| 258 |
+
d285d057636c3cba2d1fd3b37693b18075ad4b9c3b47bbde807c34c6c376ac93 openpi-umi/src/openpi/models/vit.py
|
| 259 |
+
08fd8d750519f0fb44fc5173311e50a30f4c8f32c02e51244b4f8e47b32cd52f openpi-umi/src/openpi/models_pytorch/gemma_pytorch.py
|
| 260 |
+
0c7b9f1de02ed886da49035e3fa1b38efea46eb6209489cb4f594f777f97b70c openpi-umi/src/openpi/models_pytorch/pi0_pytorch.py
|
| 261 |
+
6a44e91be2d7a724c6140d2cc98ed0a631b8d38bbb29f63b380a0a19f903bbf6 openpi-umi/src/openpi/models_pytorch/preprocessing_pytorch.py
|
| 262 |
+
26fd0d0f52730ab32b6f337eb73ae9a26cb71ae0915bc49eced1d0e2ed8d0ec6 openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py
|
| 263 |
+
17eeb54e277939e58cd6f8a92719a275e36baf0c9f463b2754227d42f87aedde openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py
|
| 264 |
+
c945d330b829264f927f3ee5339f977238631772de07a28e855e265bb85fd53c openpi-umi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py
|
| 265 |
+
466e8eb7887ac5ccc98118a3169298d6ab65a284d834bae74751e3854dbc4245 openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py
|
| 266 |
+
ef2e99500f263fdd78db9d4d9a255e29d844eb92f53c25ad640f8056700ef84b openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py
|
| 267 |
+
50d7ad972d80142ecb0f03b0780dacfd3af212946f4c9aac31a204b02db4543d openpi-umi/src/openpi/policies/aloha_policy.py
|
| 268 |
+
7d0893555964d485e231f70084125084a99495705ddd74b29461229d524fff26 openpi-umi/src/openpi/policies/droid_policy.py
|
| 269 |
+
ad01e5be74516d9ec9aeb1f76294d5c9f7f7179a60f1f7fbbb35e7646534f81a openpi-umi/src/openpi/policies/libero_policy.py
|
| 270 |
+
a2ac5236e23b11d0f5a840d4a8fef148d89dba921d5452ec5dfcd5a6ffa46f20 openpi-umi/src/openpi/policies/policy.py
|
| 271 |
+
dc4202b420676ca9af61a141b1096dfd1efced635d06d4846e9a0537b8ded288 openpi-umi/src/openpi/policies/policy_config.py
|
| 272 |
+
9dbb20963600367a7e7abfc97d1e326916777c57a87b39b1bc4070ba64676683 openpi-umi/src/openpi/policies/policy_test.py
|
| 273 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/py.typed
|
| 274 |
+
1370d345e6c3c5b8f15573050e485e60a5b423d1df33e24b237805e6b442b026 openpi-umi/src/openpi/serving/websocket_policy_server.py
|
| 275 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/shared/__init__.py
|
| 276 |
+
6524945566eab3eb97b75a6280ba4724617b4d028c55f05172b283c3de68a026 openpi-umi/src/openpi/shared/array_typing.py
|
| 277 |
+
8711d466cdaec488633e5509a000af6a7411b2d56f7ce6161f718f2389aa7786 openpi-umi/src/openpi/shared/download.py
|
| 278 |
+
234ee70ab2501a1421f6c44cbd83c1e16747597023319ae1446bed9d44f17072 openpi-umi/src/openpi/shared/download_test.py
|
| 279 |
+
0f8fcb355288119e56acb56d550c1cc1f3a9edddceb0dc5b319f955943ef7767 openpi-umi/src/openpi/shared/image_tools.py
|
| 280 |
+
842374579dc9f4c2907da5e8bb555efe5a3f4902b659720c8e90115863dd59fe openpi-umi/src/openpi/shared/image_tools_test.py
|
| 281 |
+
4da7111ba3011c4d1c381c9ed17257771df6a50ed89182647c3fb6f79208005e openpi-umi/src/openpi/shared/nnx_utils.py
|
| 282 |
+
6c2cea4946fb07e51801530400d2b2fd94730e195cd290d6b6960114eca9739d openpi-umi/src/openpi/shared/normalize.py
|
| 283 |
+
fda27a21cf37f337b12bcab71229407c2a349c5965c33f278bdc468ed03f58af openpi-umi/src/openpi/shared/normalize_test.py
|
| 284 |
+
3cc32682ec3609e9075dabd991488edb9d7f6c045443f58963d733f99c468dbd openpi-umi/src/openpi/training/checkpoints.py
|
| 285 |
+
38c5a1710c4910831bd10fd34324b880b98a63481d92af22ba3b88fdabd2a7f3 openpi-umi/src/openpi/training/config.py
|
| 286 |
+
e0de9e5caa099edb37aa1d682bbf438cc3a3fae1aea50efd37a992571efcda83 openpi-umi/src/openpi/training/data_loader.py
|
| 287 |
+
a0cf1bc293e8b0eb9bc5516bc05d30d9940da06c94fcfa1addca7267f8358815 openpi-umi/src/openpi/training/data_loader_test.py
|
| 288 |
+
1d3a057a040240218234d7dbc6680ee4fe8256f2058531a0f9fefd3f7ee995a4 openpi-umi/src/openpi/training/droid_rlds_dataset.py
|
| 289 |
+
c2ab92efb5e0d675118ad812113fd1c3cb3a62cdab5d79066014266e82df12d8 openpi-umi/src/openpi/training/misc/polaris_config.py
|
| 290 |
+
914acdd74ccf90e6779c13a5093140595c7e4f687e9e0b167439446a81d74c01 openpi-umi/src/openpi/training/misc/roboarena_config.py
|
| 291 |
+
603ee4ce4d5f727872840557004b047b7dccbcf86d86263558952bf617e6fd26 openpi-umi/src/openpi/training/optimizer.py
|
| 292 |
+
c67c4112a126ab097571c8a882fd1ee3f106b15b6e608e7205ac7f29b44ca985 openpi-umi/src/openpi/training/sharding.py
|
| 293 |
+
7b9a4b0b09b040cb88c9e99700f8d3a7cca129db08584edebd3b0f8558bae5d4 openpi-umi/src/openpi/training/umi_data.py
|
| 294 |
+
60bce67368e855fec1d55bde128d32e90cfe07b82f57cdc1d639e3efda0dd1fd openpi-umi/src/openpi/training/umi_data_test.py
|
| 295 |
+
9b67c127451104e37535581c40870e43bd502da4e5f1bfc0da98f36dbf427472 openpi-umi/src/openpi/training/umi_v3_dataset.py
|
| 296 |
+
9893f2a84147b938df4508e6a930c278ce4366c093e37585b1e5e0d1a11f9448 openpi-umi/src/openpi/training/umi_v3_dataset_test.py
|
| 297 |
+
b684e674343f86ef5e976f279a586d3fe2f885e901f396ac899ed136abc7eca6 openpi-umi/src/openpi/training/utils.py
|
| 298 |
+
a54ac3222f81f8c6233241bc16b6f369c9416cdaa83f7058f96f7ddcfde1a3b4 openpi-umi/src/openpi/training/weight_loaders.py
|
| 299 |
+
707425a385306ca6debd01dbaa0323a6214db56d101830114d97c6af9e944c4d openpi-umi/src/openpi/transforms.py
|
| 300 |
+
d76f3ee8c5d7dc1c6fb6cb3b36b45ef30dd1de1ab5bc054bcb03deb79dcc06a8 openpi-umi/src/openpi/transforms_test.py
|
| 301 |
+
5e3a9a0a12d9a6048afea5591f4520c98585499cbd4a8343dcabfe2aaed94e3d openpi-umi/uv.lock
|
| 302 |
+
64eee33af95370863538323cfa58013adb4242ed5e91722e9d2ee1b6c2e19f09 scripts/mock_roundtrip.py
|
| 303 |
+
62ee3cdc906e4c4f6a5f61380ed008122fb578ac3e8881685900548f2daed5de scripts/run_flux_server.sh
|
| 304 |
+
5329fa1de87f2bf0ca6f07ae47dc5ff3de227f285add740271e6de85d26553d5 scripts/run_pi05_server.sh
|
| 305 |
+
4899458d570b0b56eaf029cbe47175a6cede66d820ed09290c010f807159d604 scripts/run_robot.sh
|
| 306 |
+
d5882b05e35e5ef1623c904e1620ec0d37aa1287ef5113cf6cf95abc8e85882f scripts/test_release_assets.py
|
| 307 |
+
f0efd493273087599d3e02d6f4dd59ceef6139bf115cc9a8f54cecc307ebe898 scripts/verify_assets.py
|
configs/inference.env.example
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copy to a PRIVATE file and source it in the matching environment.
|
| 2 |
+
# Never distribute the filled file, credentials, device serials or runtime recordings.
|
| 3 |
+
FLUX_EXPORT_DIR=/path/to/checkpoints/flux_fold_clothes_bf16
|
| 4 |
+
FLUX_RESOURCES=/path/to/flux_resources
|
| 5 |
+
PI05_CHECKPOINT_DIR=/path/to/checkpoints/pi05_fold_clothes/epoch_2
|
| 6 |
+
TOKENIZER_DIR=/path/to/tokenizer_root
|
| 7 |
+
UMI_INFER_DATA=/path/to/cell_data
|
| 8 |
+
TASK_PROMPT="fold the clothes"
|
| 9 |
+
SERVER_URI=ws://127.0.0.1:8765
|
| 10 |
+
SERVER_HOST=127.0.0.1
|
| 11 |
+
SERVER_PORT=8765
|
| 12 |
+
DEVICE=cuda:0
|
| 13 |
+
# Explicit reference settings. They mirror this source's CLI defaults, not a verified video recipe.
|
| 14 |
+
FLUX_SAMPLER=euler
|
| 15 |
+
FLUX_STEPS=4
|
| 16 |
+
FLUX_SHIFT=42
|
| 17 |
+
FLUX_GUIDANCE=1.0
|
| 18 |
+
FLUX_ACTION_GUIDANCE=1.0
|
| 19 |
+
FLUX_SEED=0
|
| 20 |
+
PI05_DENOISE_STEPS=10
|
| 21 |
+
# Optional Python executables for separate environments:
|
| 22 |
+
#FLUX_PYTHON=/path/to/flux_env/bin/python
|
| 23 |
+
#PI05_PYTHON=/path/to/pi05_env/bin/python
|
| 24 |
+
#ROBOT_PYTHON=/path/to/robot_env/bin/python
|
docs/CHECKPOINTS_FLUX.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Cloth-folding inference checkpoint
|
| 2 |
+
|
| 3 |
+
The following inventory was provided by the model owner. Weight bytes and the remote manifest/config have not been independently downloaded or validated during this documentation update. Internal job IDs, experiment names, bucket names and training-storage paths are intentionally omitted from this public document.
|
| 4 |
+
|
| 5 |
+
## Provided export
|
| 6 |
+
|
| 7 |
+
```text
|
| 8 |
+
checkpoints/flux_fold_clothes_bf16/
|
| 9 |
+
config.json
|
| 10 |
+
manifest.json
|
| 11 |
+
model.safetensors
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
- Format: already exported inference policy, BF16; **do not export it again merely to run inference**.
|
| 15 |
+
- Selected checkpoint: step 14418, model weights (not asserted to be EMA).
|
| 16 |
+
- Reported weight-file size: 13,894,466,592 bytes.
|
| 17 |
+
- Earlier training checkpoints at steps 4806 and 9612 were reported in training storage; only the final step was reported in the supplied remote export.
|
| 18 |
+
- The 16-GPU training template in this source archive is not evidence of this checkpoint's exact training configuration. The supplied experiment label suggests a different worker/window/epoch setup; obtain the actual train configuration rather than treating that template as the rollout recipe.
|
| 19 |
+
|
| 20 |
+
## Loading
|
| 21 |
+
|
| 22 |
+
`flux-action infer` accepts this **export directory**, not a raw training `step-N` directory. `FluxActionPolicy.from_pretrained` reads the policy config and verifies the manifest against config/model bytes. Keep the three files together; if any file is changed, a matching manifest must be generated by the proper export path.
|
| 23 |
+
|
| 24 |
+
The supplied inventory lists only policy weights/config/manifest. The VAE and text encoder are separate requirements of the policy code. Resolve the locations referenced by `config.json` and verify that they are accessible in the inference environment. A policy-weight export alone does not establish that encoder assets are bundled.
|
| 25 |
+
|
| 26 |
+
Read sampler, num_inference_steps, guidance_scale, guidance_scale_action and sampler_shift from the actual export config; do not replace them with guessed settings from a training template. The model owner reports this export as ready for inference; the current source still validates those fields at load/inference time.
|
| 27 |
+
|
| 28 |
+
Once the matching environment, encoder assets and a correctly prepared UMI observation NPZ are available:
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
flux-action infer --checkpoint /path/to/checkpoints/flux_fold_clothes_bf16 --observation /path/to/umi_observation.npz --task "fold the clothes" --output /path/to/new_inference_output --device cuda
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
The NPZ must use the export's camera keys and 20-D UMI relative state; a raw 16-D pose is not the model state. A UMI robot adapter must restore anchor-relative action chunks and handle robot coordinates/grippers. This command is a documented interface, not a new runtime validation of the remote weights.
|
| 35 |
+
|
| 36 |
+
## Weight release checks
|
| 37 |
+
|
| 38 |
+
Before distributing the actual checkpoint, inspect config strings for internal encoder/checkpoint paths. Changing `config.json` to portable locations requires regenerating its manifest hash; silently editing config while retaining the old manifest will fail integrity checks. This documentation update does not modify or redistribute the remote weights.
|
docs/CHECKPOINTS_PI05.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# π0.5 cloth-folding inference checkpoint
|
| 2 |
+
|
| 3 |
+
This inventory was supplied by the model owner. Remote model bytes and metadata have not been downloaded or executed during this documentation update. Public paths below are neutral examples; internal job IDs, experiment names and storage addresses are omitted.
|
| 4 |
+
|
| 5 |
+
## Provided checkpoint
|
| 6 |
+
|
| 7 |
+
```text
|
| 8 |
+
checkpoints/pi05_fold_clothes/epoch_2/
|
| 9 |
+
model.safetensors
|
| 10 |
+
metadata.pt
|
| 11 |
+
assets/umi_v3/norm_stats.json
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
- Model/config family: π0.5, `pi05_umi_v3`.
|
| 15 |
+
- Selected checkpoint: epoch 2; epoch 1 was also reported in training storage, but only epoch 2 was reported in the supplied remote location.
|
| 16 |
+
- Reported model-file size: 7,473,091,464 bytes.
|
| 17 |
+
- `optimizer.pt` is not in the reported copy. Its absence does **not** prevent inference; it does prevent an exact optimizer-state training resume from that copy alone.
|
| 18 |
+
- Use `assets/umi_v3/norm_stats.json` from this checkpoint. Do not replace it with statistics recomputed from the one-hour sample.
|
| 19 |
+
- `metadata.pt` is supplied for checkpoint metadata; the generic `create_trained_policy` PyTorch path is driven by the training/model config, safetensors weights and normalization statistics. It does not require loading optimizer state for inference.
|
| 20 |
+
|
| 21 |
+
## Training information and provenance
|
| 22 |
+
|
| 23 |
+
The supplied experiment label indicates 16 workers, global batch 1280 (80 per worker), 2 epochs, action horizon 50, peak LR 7.5e-5, zero warmup, a 1.5-epoch hold and linear cooldown. These are label-derived details, not a replacement for the saved run configuration. Confirm them against the run configuration before presenting them as a fully reproduced experiment.
|
| 24 |
+
|
| 25 |
+
The existing shell launcher is single-node. The README's 8-worker command is a portable example, not the reported 16-worker run. Do not present it as the exact multi-node launch used for the video.
|
| 26 |
+
|
| 27 |
+
## Policy construction
|
| 28 |
+
|
| 29 |
+
Prepare the patched transformers environment described in the main README. With a compatible runtime, the generic loading interface is:
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
from openpi.policies import policy_config
|
| 34 |
+
from openpi.training import config as training_config
|
| 35 |
+
|
| 36 |
+
checkpoint = Path("/path/to/checkpoints/pi05_fold_clothes/epoch_2")
|
| 37 |
+
config = training_config.get_config("pi05_umi_v3")
|
| 38 |
+
data_config = config.data.create(config.assets_dirs, config.model)
|
| 39 |
+
policy = policy_config.create_trained_policy(
|
| 40 |
+
config,
|
| 41 |
+
checkpoint,
|
| 42 |
+
repack_transforms=data_config.repack_transforms,
|
| 43 |
+
norm_stats_path=checkpoint / "assets/umi_v3/norm_stats.json",
|
| 44 |
+
pytorch_device="cuda",
|
| 45 |
+
)
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
This illustrates the existing API and explicit UMI repack/statistics wiring. It has not been run against the remote weights. `policy.infer` still needs both wrist images, previous/current 16-D pose states, and the prompt in the agreed observation schema. It returns a model-space action chunk, not directly executable Flexiv commands. A robot adapter must preserve the per-chunk anchors and restore absolute target poses with the correct calibration and gripper units.
|
docs/INFERENCE_CONTRACT.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Input/output and frame contract
|
| 2 |
+
|
| 3 |
+
Robot IO reads both wrists and two proprio frames `[previous,current]`, one native model frame apart in executed progress. Wire poses are `[x,y,z,qx,qy,qz,qw]`; Flexiv native poses are wxyz and the IO handles that boundary. The dataset is a camera optical-frame pose, not automatically a robot flange pose.
|
| 4 |
+
|
| 5 |
+
For each hand, E = inverse(T_flange_camera):
|
| 6 |
+
|
| 7 |
+
- Model camera input: `T_world_camera = T_world_flange @ inverse(E)`.
|
| 8 |
+
- Relative training state: `inverse(T_current_camera) @ T_previous_camera`, current gripper.
|
| 9 |
+
- Relative target: `inverse(T_current_camera) @ T_future_camera`.
|
| 10 |
+
- Robot target: `T_current_camera @ T_predicted_relative @ E`.
|
| 11 |
+
|
| 12 |
+
20 dimensions total: each hand uses translation3 + first-two-rotation-columns6 + gripper1. Raw pose buffers are16 dimensions, wxyz, metres, gripper degrees; they must be encoded. Anchor each chunk using the same current pose captured when its observation was made. No cross-hand common SLAM world frame is assumed by the training input.
|
| 13 |
+
|
| 14 |
+
FLUX uses32 steps /30Hz and both wrist images. π0.5 uses50 model steps with a32-D model head padded from20-D UMI targets; its adapter returns20-D actions and restores absolute camera poses, then flange poses. Optional upsampling changes sample count/dt; robot-side playback scaling changes wall time without redefining the model's previous/current state contract. Local servo cadence is separate from request cadence.
|
| 15 |
+
|
| 16 |
+
This sample's Observation/Action msgpack protocol is defined in `flexiv-umi-infer/umi_infer/protocol.py`. Generic OpenPI clients use a different wire envelope. Use the provided robot_agent and policy_server together.
|
docs/VALIDATION.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 验证范围
|
| 2 |
+
|
| 3 |
+
源码已完成语法检查、离线接口与记录测试、配置资产检查及mock协议往返验证。实际部署需结合模型资源、设备环境及标定进行集成验证。
|
docs/validation.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"python_syntax_files": 245,
|
| 3 |
+
"shell_syntax_files": 5,
|
| 4 |
+
"forbidden_matches": [],
|
| 5 |
+
"git_entries": [],
|
| 6 |
+
"urdf_sha256": "6d05cf21d13cf85ad7fcede2fb4eb615052d616341f1065b59caf41f9a749398",
|
| 7 |
+
"omitted_display_media": [
|
| 8 |
+
"flux-umi/docs/assets/flux-3-action-hero.webp",
|
| 9 |
+
"flux-umi/examples/games/assets/grunt_step3000.gif",
|
| 10 |
+
"flux-umi/examples/games/assets/vector_step3000.gif"
|
| 11 |
+
],
|
| 12 |
+
"offline_tests_passed": 8,
|
| 13 |
+
"asset_preflight_tests_passed": 2,
|
| 14 |
+
"in_process_roundtrips_passed": 3,
|
| 15 |
+
"real_weights_loaded": false,
|
| 16 |
+
"hardware_tested": false,
|
| 17 |
+
"full_flux_model_test_suite_run": false
|
| 18 |
+
}
|
flexiv-umi-infer/.gitignore
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
*.egg-info/
|
| 5 |
+
cell.env
|
| 6 |
+
data/*
|
| 7 |
+
!data/.gitkeep
|
| 8 |
+
rollouts/
|
| 9 |
+
tools/insta360_cli_dual
|
| 10 |
+
weights/
|
flexiv-umi-infer/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.
|
flexiv-umi-infer/README.md
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 中文 / English
|
| 2 |
+
|
| 3 |
+
[中文](#zh) · [English](#en)
|
| 4 |
+
|
| 5 |
+
<a id="zh"></a>
|
| 6 |
+
|
| 7 |
+
# flexiv-umi-infer · 双臂UMI实机推理
|
| 8 |
+
|
| 9 |
+
用于Flexiv Rizon4双臂平台,配置两台Insta360 X4 Air腕载相机及两只达妙电机夹爪。支持[OpenPI / π0.5](../openpi-umi)、[FLUX](../flux-umi)或mock策略。包含名义双臂URDF,不含权重、数据集、mesh及现场标定;使用入口见[上级说明](../README.md)。
|
| 10 |
+
|
| 11 |
+
## 工作方式
|
| 12 |
+
|
| 13 |
+
机器人电脑运行`robot_agent`与Flexiv IO,GPU机器运行`policy_server`。双方通过WebSocket传输msgpack消息(`umi_infer/protocol.py`):Observation包括两路腕相机、前一帧/当前帧TCP位姿及夹爪;Action包括法兰位姿块、夹爪开度及dt。机器人本地伺服线程为100Hz。
|
| 14 |
+
|
| 15 |
+
- 默认同步推理:执行完一个动作块后,采集新观测并请求下一块。
|
| 16 |
+
- IK由Flexiv控制器执行;IO使用`NRT_CARTESIAN_MOTION_FORCE`下发世界系TCP位姿,`Model.reachable`仅作预检查。
|
| 17 |
+
- 数据位姿属于腕相机光学系。每臂外参`E = inv(T_flange_cam)`;输入`T_cam = T_flange @ E^-1`,输出`T_flange = T_cam @ E`。
|
| 18 |
+
- 观测中的`[prev, cur]`相隔一个原生模型帧(1/30秒);这里指已执行进度,不是墙钟时间。
|
| 19 |
+
- 默认回放时间缩放为2.5倍,以满足控制器加速度限制,不改变模型dt或状态含义。
|
| 20 |
+
|
| 21 |
+
## 代码结构
|
| 22 |
+
|
| 23 |
+
| 路径 | 职责 |
|
| 24 |
+
| --- | --- |
|
| 25 |
+
| umi_infer/policy_server.py | 策略创建与WebSocket服务 |
|
| 26 |
+
| umi_infer/robot_agent.py | 机器人控制循环 |
|
| 27 |
+
| umi_infer/protocol.py | Observation / Action消息 |
|
| 28 |
+
| umi_infer/policies/ | π0.5、FLUX和mock策略 |
|
| 29 |
+
| umi_infer/codec/ | π0.5推理、相对动作解码、样条上采样 |
|
| 30 |
+
| umi_infer/robot_io/flexiv.py | 双臂预检查、伺服线程与记录 |
|
| 31 |
+
| umi_infer/robot_io/insta_live.py | CameraSDK CLI → FIFO → ffmpeg相机流 |
|
| 32 |
+
| umi_infer/robot_io/gripper_can.py、gripper_tool.py | 夹爪伺服与CAN扫描/读取/标定 |
|
| 33 |
+
| umi_infer/robot_io/rollout_rec.py | 逐帧rollout记录 |
|
| 34 |
+
| urdf/flexiv_rizon4_dual_umi.urdf | 默认双臂名义URDF |
|
| 35 |
+
| umi_infer/export_E.py | 从URDF导出左右E及来源记录 |
|
| 36 |
+
| umi_infer/check_cam.py | 相机自检 |
|
| 37 |
+
| tools/insta360_cli_dual.cc | 相机CLI,构建见[tools说明](tools/README.md) |
|
| 38 |
+
|
| 39 |
+
## 安装与配置
|
| 40 |
+
|
| 41 |
+
机器人电脑安装`.[robot]`;GPU环境按策略分别安装`.[pi05]`与相邻OpenPI项目,或`.[flux]`与相邻FLUX项目。Flexiv SDK另行安装:`flexivdrdk`需配合`flexivrdk` 1.9.x,2.x在`RobotPair.states()`存在崩溃问题;必须先导入flexivrdk。每台机器人仅接受一个RDK连接,运行前关闭其他连接。
|
| 42 |
+
|
| 43 |
+
复制`configs/cell.env.example`为私有配置,填写机械臂与相机序列号、`UMI_INFER_DATA`(默认`data/`),再用`set -a; source cell.env; set +a`加载。标定目录需包含:
|
| 44 |
+
|
| 45 |
+
| 文件 | 生成方式 |
|
| 46 |
+
| --- | --- |
|
| 47 |
+
| E_left.npy、E_right.npy、E_from_urdf.json | `python -m umi_infer.export_E`,URDF每次变化均需重导 |
|
| 48 |
+
| gripper_calib.json | `python -m umi_infer.robot_io.gripper_tool calib --motor 0:8 --motor 1:8 --yes` |
|
| 49 |
+
| anchor.json | 按实际起始姿态填写configs/anchor.example.json |
|
| 50 |
+
|
| 51 |
+
CANalyst-II通道0为左臂、通道1为右臂;电机命令ID为0x08、反馈ID为0x18。`gripper_tool scan`扫描电机,`--help`提供udev访问说明。
|
| 52 |
+
|
| 53 |
+
名义URDF由立柱悬挂的Rizon4/Rizon4R、FT03腕传感器和UMI夹爪构成,基座y=±0.25m,世界原点在法兰之间。机械臂mesh引用`package://flexiv_description/...`;夹爪只包含相机、TCP和指尖运动学坐标。相机外参为CAD值;使用实测运动学或手眼标定时,保留link名称并通过`FLEXIV_URDF`指定现场URDF。`E_from_urdf.json`记录CAD或标定来源。起始姿态应使腕相机视角接近训练episode起点。
|
| 54 |
+
|
| 55 |
+
## 运行命令
|
| 56 |
+
|
| 57 |
+
以下依次为安装、自检、GPU服务、机器人dry run、实机运行与测试命令;两种模型使用独立环境。
|
| 58 |
+
|
| 59 |
+
```
|
| 60 |
+
robot PC GPU box
|
| 61 |
+
robot_agent ── Observation (2 wrist images, ──────> policy_server
|
| 62 |
+
FlexivRobotIO [prev, cur] TCP poses, grippers) pi05 | flux | mock
|
| 63 |
+
100 Hz servo <─────── Action (chunk of flange ───
|
| 64 |
+
thread poses + gripper openings, dt)
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
# robot PC (needs Flexiv flexivrdk 1.9.x + flexivdrdk, installed separately)
|
| 69 |
+
pip install -e ".[robot]"
|
| 70 |
+
# GPU box
|
| 71 |
+
pip install -e ".[pi05]" && pip install -e ../openpi-umi # π0.5
|
| 72 |
+
pip install -e ".[flux]" && pip install -e ../flux-umi # FLUX
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
# 0. checks
|
| 77 |
+
python -m umi_infer.check_cam --dataset /data/umi_v3/episode_0000 # both cameras, compare with training
|
| 78 |
+
python -m umi_infer.robot_io.gripper_tool read --motor 0:8 --motor 1:8 # motors stay disabled; move the jaws by hand
|
| 79 |
+
|
| 80 |
+
# 1. policy server (GPU box)
|
| 81 |
+
python -m umi_infer.policy_server --policy pi05 --checkpoint-dir /ckpt/run/epoch_2 \
|
| 82 |
+
--eef-extrinsic-left data/E_left.npy --eef-extrinsic-right data/E_right.npy --prompt "fold the clothes"
|
| 83 |
+
python -m umi_infer.policy_server --policy flux --flux-export /ckpt/flux_export \
|
| 84 |
+
--flux-resources /ckpt/flux_resources --flux-e-left data/E_left.npy --flux-e-right data/E_right.npy \
|
| 85 |
+
--flux-e-provenance data/E_from_urdf.json --flux-prompt "fold the clothes" \
|
| 86 |
+
--flux-sampler euler --flux-steps 4 --flux-shift 42 --flux-guidance 1.0 --flux-action-guidance 1.0
|
| 87 |
+
|
| 88 |
+
# 2. robot agent (robot PC), dry run first: full pipeline, no motion commands
|
| 89 |
+
python -m umi_infer.robot_agent --io flexiv --live-camera --server ws://127.0.0.1:8765 \
|
| 90 |
+
--record /tmp/run.csv
|
| 91 |
+
# 3. live, with grippers. Keep a hand on the e-stop.
|
| 92 |
+
python -m umi_infer.robot_agent --io flexiv --live-camera --live --gripper --server ws://127.0.0.1:8765
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
pip install -e ".[mock,dev]"
|
| 97 |
+
python -m pytest tests/test_flexiv_trace.py tests/test_rollout_rec.py # no hardware needed
|
| 98 |
+
python -m pytest tests/test_flux_action_dual.py # needs torch + flux-umi
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
π0.5默认从`gs://big_vision`加载PaliGemma tokenizer;离线机器应通过`TOKENIZER_DIR`提供包含`paligemma-3b-pt-224/tokenizer.model`的目录。FLUX机器人端增加`--cam-format yuv420p --cam-kbps 30720`,由策略端按训练同样的PyAV路径将I420转RGB。服务默认绑定127.0.0.1,跨机器运行时设置`--host 0.0.0.0`。无硬件时使用`--policy mock`与`--io mock`。
|
| 102 |
+
|
| 103 |
+
常用机器人参数:`--play-scale`(默认2.5)、`--first-steps`/`--steps`(执行每块前N步)、`--kx-ratio`(笛卡尔刚度)、`--nullspace-weight`(肘部刚度)、`--grip-offset-deg`(调整夹爪角度)。
|
| 104 |
+
|
| 105 |
+
## 控制保护与约定
|
| 106 |
+
|
| 107 |
+
| 保护 | 说明 |
|
| 108 |
+
| --- | --- |
|
| 109 |
+
| Dry run | 未指定--live时只作预检查与插值,不下发动作 |
|
| 110 |
+
| 自碰撞监测 | SelfCollisionMonitor按link距离检查并停止双臂,不包含夹爪 |
|
| 111 |
+
| 工具预检查 | 按夹爪点间距检查,参数--tool-min-dist |
|
| 112 |
+
| 逐周期保护 | 故障、外部控制模式切换和TCP间距--min-dist |
|
| 113 |
+
| 动作块检查 | 有限值、最大步长--max-step-mm、可达性--ik-check |
|
| 114 |
+
| 关节限位 | 起始姿态距硬限位至少0.5° |
|
| 115 |
+
| 夹爪力限制 | 目标角度限制在实测角度±lead,扭矩≤kp×lead |
|
| 116 |
+
|
| 117 |
+
距离阈值默认2cm,新平台需调整;夹爪约超出法兰16cm,不包含在自碰撞模型中。进入力控前本次会话清零腕F/T传感器,否则可能出现Flexiv错误301004。
|
| 118 |
+
|
| 119 |
+
`RobotPair.states().tcp_pose`与`SendCartesianMotionForce`共用世界系;TCP为法兰,控制器不设置工具偏移。Flexiv四元数为wxyz,传输为xyzw,仅在`_w2x`/`_x2w`转换。夹爪以度表示,0闭合、90全开;DRDK机械臂顺序均为(left,right)。
|
| 120 |
+
|
| 121 |
+
## 记录、测试与许可
|
| 122 |
+
|
| 123 |
+
`--record run.csv`记录每个伺服tick的命令/实测位姿,`run.chunks.jsonl`记录模型输出与预检查。未指定`--no-rollout`时,在`--rollout-root`下记录伺服频率低维数据与腕相机帧。服务器`--record-dir`保存收到的图像及逐次推理记录,双方通过seq关联。离线轨迹/记录测试不需要硬件;FLUX策略测试需要torch及flux-umi。
|
| 124 |
+
|
| 125 |
+
许可证为Apache-2.0;Flexiv RDK、CameraSDK、OpenPI和FLUX保留各自许可。采样参数可在启动脚本中按模型与任务配置。名义URDF相机外参与rollout在1e-6内一致,但整文件哈希不同,现场完整运动学需核对。运行记录中的设备标识、时间与路径需在外发前清理。
|
| 126 |
+
|
| 127 |
+
---
|
| 128 |
+
|
| 129 |
+
<a id="en"></a>
|
| 130 |
+
|
| 131 |
+
# flexiv-umi-infer
|
| 132 |
+
|
| 133 |
+
Real-robot inference for bimanual UMI policies on a Flexiv Rizon4 dual-arm cell with two Insta360 X4 Air
|
| 134 |
+
wrist cameras and two Damiao-motor grippers. It runs policies trained with
|
| 135 |
+
[openpi-umi](../openpi-umi) (π0.5) or [flux-umi](../flux-umi) (FLUX 3 Action).
|
| 136 |
+
|
| 137 |
+
The nominal dual-arm URDF is included. Model weights, datasets, mesh assets and per-cell calibration files are not included. See the [installation and deployment guide](../README.md) for environments, model resources and launch scripts.
|
| 138 |
+
|
| 139 |
+
## How it works
|
| 140 |
+
|
| 141 |
+
Two processes talk over a websocket (msgpack, `umi_infer/protocol.py`):
|
| 142 |
+
|
| 143 |
+
```
|
| 144 |
+
robot PC GPU box
|
| 145 |
+
robot_agent ── Observation (2 wrist images, ──────> policy_server
|
| 146 |
+
FlexivRobotIO [prev, cur] TCP poses, grippers) pi05 | flux | mock
|
| 147 |
+
100 Hz servo <─────── Action (chunk of flange ───
|
| 148 |
+
thread poses + gripper openings, dt)
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
- **Sync inference (default).** The agent executes the whole chunk, takes a fresh observation and asks
|
| 152 |
+
for the next chunk, so the policy always plans from the current state.
|
| 153 |
+
- **IK runs in the Flexiv controller.** The IO switches to `NRT_CARTESIAN_MOTION_FORCE` and streams
|
| 154 |
+
world-frame TCP poses. `flexivrdk.Model.reachable` is only used as a precheck before sending.
|
| 155 |
+
- **Data frame vs. robot frame.** The dataset end effector is the wrist camera optical frame. The policy
|
| 156 |
+
side maps it to the flange with a per-arm extrinsic `E = inv(T_flange_cam)`:
|
| 157 |
+
inputs `T_cam = T_flange @ E^-1`, outputs `T_flange = T_cam @ E`.
|
| 158 |
+
- **Motion window.** The observation carries two real proprio frames `[prev, cur]`, one native frame
|
| 159 |
+
(1/30 s) apart. "One frame" means executed progress, not wall-clock time, so slow playback does not
|
| 160 |
+
change what the model sees.
|
| 161 |
+
- **Playback scale.** Each step is stretched on the wall clock (default 2.5×) so that model trajectories
|
| 162 |
+
stay within the controller's acceleration limits. `dt` and the state are unchanged.
|
| 163 |
+
|
| 164 |
+
## Layout
|
| 165 |
+
|
| 166 |
+
| Path | Contents |
|
| 167 |
+
|---|---|
|
| 168 |
+
| `umi_infer/policy_server.py` | websocket server, builds the policy |
|
| 169 |
+
| `umi_infer/robot_agent.py` | control loop on the robot PC |
|
| 170 |
+
| `umi_infer/protocol.py` | Observation / Action messages |
|
| 171 |
+
| `umi_infer/policies/` | `umi_pi05_dual.py` (π0.5), `flux_action_dual.py` (FLUX), `mock.py` |
|
| 172 |
+
| `umi_infer/codec/` | π0.5 inference core, relative-action decoding, spline upsampling |
|
| 173 |
+
| `umi_infer/robot_io/flexiv.py` | Flexiv dual-arm IO: prechecks, servo thread, recording |
|
| 174 |
+
| `umi_infer/robot_io/insta_live.py` | live wrist camera streams (CameraSDK CLI → fifo → ffmpeg) |
|
| 175 |
+
| `umi_infer/robot_io/gripper_can.py`, `gripper_tool.py` | gripper servo and CAN tool (scan / read / calib) |
|
| 176 |
+
| `umi_infer/robot_io/rollout_rec.py` | per-frame rollout recording |
|
| 177 |
+
| `urdf/flexiv_rizon4_dual_umi.urdf` | default dual-arm URDF |
|
| 178 |
+
| `umi_infer/export_E.py` | exports `E_left.npy` / `E_right.npy` from the URDF |
|
| 179 |
+
| `umi_infer/check_cam.py` | camera self-check |
|
| 180 |
+
| `tools/insta360_cli_dual.cc` | camera CLI source ([build](tools/README.md)) |
|
| 181 |
+
|
| 182 |
+
## Install
|
| 183 |
+
|
| 184 |
+
```bash
|
| 185 |
+
# robot PC (needs Flexiv flexivrdk 1.9.x + flexivdrdk, installed separately)
|
| 186 |
+
pip install -e ".[robot]"
|
| 187 |
+
# GPU box
|
| 188 |
+
pip install -e ".[pi05]" && pip install -e ../openpi-umi # π0.5
|
| 189 |
+
pip install -e ".[flux]" && pip install -e ../flux-umi # FLUX
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
`flexivdrdk` must be paired with `flexivrdk` 1.9.x (2.x segfaults in `RobotPair.states()`). The code
|
| 193 |
+
imports `flexivrdk` before `flexivdrdk`, which the bindings require. A robot accepts only one RDK
|
| 194 |
+
connection at a time, so close Flexiv Elements sessions and other scripts first.
|
| 195 |
+
|
| 196 |
+
## Configuration
|
| 197 |
+
|
| 198 |
+
Copy `configs/cell.env.example` to `cell.env`, fill it in and load it with `set -a; source cell.env; set +a`.
|
| 199 |
+
It sets the arm serials, the camera serials and the data directory (`UMI_INFER_DATA`,
|
| 200 |
+
default `data/`). The data directory holds:
|
| 201 |
+
|
| 202 |
+
| File | How to make it |
|
| 203 |
+
|---|---|
|
| 204 |
+
| `E_left.npy`, `E_right.npy`, `E_from_urdf.json` | `python -m umi_infer.export_E` (rerun after every URDF change) |
|
| 205 |
+
| `gripper_calib.json` | `python -m umi_infer.robot_io.gripper_tool calib --motor 0:8 --motor 1:8 --yes` |
|
| 206 |
+
| `anchor.json` | copy `configs/anchor.example.json` and fill in the start posture |
|
| 207 |
+
|
| 208 |
+
Grippers: CANalyst-II channel 0 = left arm, channel 1 = right arm, motor command ID 0x08 (feedback 0x18).
|
| 209 |
+
Run `gripper_tool scan` to find the motors, and `gripper_tool --help` for udev setup without sudo.
|
| 210 |
+
|
| 211 |
+
`urdf/flexiv_rizon4_dual_umi.urdf` is the default model: two Rizon4/Rizon4R arms with FT03 wrist sensors,
|
| 212 |
+
hung from a column (bases at y = ±0.25 m, world origin between the flanges), each with a UMI gripper.
|
| 213 |
+
It uses the nominal Flexiv kinematics. Arm meshes are referenced as `package://flexiv_description/...`
|
| 214 |
+
([flexiv_description](https://github.com/flexivrobotics/flexiv_description)); the gripper has kinematic
|
| 215 |
+
frames only (`grip_camera_optical_frame`, `grip_tcp_link`, fingertips), which is all inference needs. The
|
| 216 |
+
camera pose is the CAD value. For per-robot kinematics or a hand-eye calibrated camera, build your own URDF
|
| 217 |
+
with the same link names and point `FLEXIV_URDF` at it (`export_E` records CAD vs. calibrated in
|
| 218 |
+
`E_from_urdf.json`).
|
| 219 |
+
|
| 220 |
+
The start posture decides what the model sees first, so pick one where the wrist views look like the
|
| 221 |
+
start of your training episodes.
|
| 222 |
+
|
| 223 |
+
## Run
|
| 224 |
+
|
| 225 |
+
```bash
|
| 226 |
+
# 0. checks
|
| 227 |
+
python -m umi_infer.check_cam --dataset /data/umi_v3/episode_0000 # both cameras, compare with training
|
| 228 |
+
python -m umi_infer.robot_io.gripper_tool read --motor 0:8 --motor 1:8 # motors stay disabled; move the jaws by hand
|
| 229 |
+
|
| 230 |
+
# 1. policy server (GPU box)
|
| 231 |
+
python -m umi_infer.policy_server --policy pi05 --checkpoint-dir /ckpt/run/epoch_2 \
|
| 232 |
+
--eef-extrinsic-left data/E_left.npy --eef-extrinsic-right data/E_right.npy --prompt "fold the clothes"
|
| 233 |
+
python -m umi_infer.policy_server --policy flux --flux-export /ckpt/flux_export \
|
| 234 |
+
--flux-resources /ckpt/flux_resources --flux-e-left data/E_left.npy --flux-e-right data/E_right.npy \
|
| 235 |
+
--flux-e-provenance data/E_from_urdf.json --flux-prompt "fold the clothes" \
|
| 236 |
+
--flux-sampler euler --flux-steps 4 --flux-shift 42 --flux-guidance 1.0 --flux-action-guidance 1.0
|
| 237 |
+
|
| 238 |
+
# 2. robot agent (robot PC), dry run first: full pipeline, no motion commands
|
| 239 |
+
python -m umi_infer.robot_agent --io flexiv --live-camera --server ws://127.0.0.1:8765 \
|
| 240 |
+
--record /tmp/run.csv
|
| 241 |
+
# 3. live, with grippers. Keep a hand on the e-stop.
|
| 242 |
+
python -m umi_infer.robot_agent --io flexiv --live-camera --live --gripper --server ws://127.0.0.1:8765
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
π0.5 loads the PaliGemma tokenizer from `gs://big_vision` unless `TOKENIZER_DIR` points at a directory
|
| 246 |
+
containing `paligemma-3b-pt-224/tokenizer.model` (set it on offline machines).
|
| 247 |
+
|
| 248 |
+
For FLUX add `--cam-format yuv420p --cam-kbps 30720` to the agent: raw I420 planes are converted to RGB on
|
| 249 |
+
the policy side with the same pyav call as training. The server binds `127.0.0.1` by default; pass
|
| 250 |
+
`--host 0.0.0.0` when the agent runs on another machine.
|
| 251 |
+
|
| 252 |
+
Without hardware, `--policy mock` and `--io mock` exercise the whole loop.
|
| 253 |
+
|
| 254 |
+
Useful agent options: `--play-scale` (default 2.5), `--first-steps` / `--steps` (execute only the first N
|
| 255 |
+
steps of each chunk), `--kx-ratio` (Cartesian stiffness), `--nullspace-weight` (elbow stiffness),
|
| 256 |
+
`--grip-offset-deg` (subtract from model gripper openings so grasps saturate the force clamp).
|
| 257 |
+
|
| 258 |
+
## Safety
|
| 259 |
+
|
| 260 |
+
All protections are on by default and must be disabled explicitly.
|
| 261 |
+
|
| 262 |
+
| Layer | Mechanism |
|
| 263 |
+
|---|---|
|
| 264 |
+
| Dry run | default without `--live`: prechecks and interpolation run, nothing is sent |
|
| 265 |
+
| Self-collision monitor | Flexiv `SelfCollisionMonitor`, link to link, stops both arms (`--monitor-min-dist`). It does not see the gripper. |
|
| 266 |
+
| Tool-aware precheck | arm-to-arm distance between gripper points before a chunk is sent (`--tool-min-dist`) |
|
| 267 |
+
| Per-cycle guard | fault, control mode changed externally, measured TCP-to-TCP distance (`--min-dist`) |
|
| 268 |
+
| Chunk prechecks | finite values, max step jump (`--max-step-mm`), vendor reachability (`--ik-check`) |
|
| 269 |
+
| Joint limit margin | the start posture must stay ≥ 0.5° inside the hardware limits |
|
| 270 |
+
| Gripper force bound | target angle stays within measured ± lead, so torque ≤ kp × lead |
|
| 271 |
+
|
| 272 |
+
The distance thresholds default to 2 cm. Raise them for a new cell. The gripper reaches about 16 cm past
|
| 273 |
+
the flange, and the monitor's collision model does not include it. Before entering force-control modes
|
| 274 |
+
the IO zeroes the wrist F/T sensors in the current session (Flexiv error 301004 otherwise).
|
| 275 |
+
|
| 276 |
+
## Conventions
|
| 277 |
+
|
| 278 |
+
| | |
|
| 279 |
+
|---|---|
|
| 280 |
+
| world frame | `RobotPair.states().tcp_pose` and `SendCartesianMotionForce` share one frame |
|
| 281 |
+
| TCP | the flange; no tool offset is configured in the controller |
|
| 282 |
+
| quaternions | Flexiv is `wxyz`, the wire protocol is `xyzw`. The IO converts only in `_w2x` / `_x2w` |
|
| 283 |
+
| gripper | dataset degrees, 0 = closed, 90 = fully open |
|
| 284 |
+
| arm order | every DRDK call takes `(left, right)` |
|
| 285 |
+
|
| 286 |
+
## Recording
|
| 287 |
+
|
| 288 |
+
With `--record run.csv` the agent writes commanded vs. measured poses per servo tick and
|
| 289 |
+
`run.chunks.jsonl` with the model output and precheck results of each chunk. Unless `--no-rollout` is
|
| 290 |
+
given, `robot_io/rollout_rec.py` also records the run under `--rollout-root`: low-dimensional data at
|
| 291 |
+
the servo rate, plus wrist frames. The server's `--record-dir` saves the received images and one line
|
| 292 |
+
per inference. Both sides join on `seq`.
|
| 293 |
+
|
| 294 |
+
## Tests
|
| 295 |
+
|
| 296 |
+
```bash
|
| 297 |
+
pip install -e ".[mock,dev]"
|
| 298 |
+
python -m pytest tests/test_flexiv_trace.py tests/test_rollout_rec.py # no hardware needed
|
| 299 |
+
python -m pytest tests/test_flux_action_dual.py # needs torch + flux-umi
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
## License
|
| 303 |
+
|
| 304 |
+
Apache-2.0. Flexiv RDK, the Insta360 CameraSDK, openpi and FLUX 3 Action keep their own licenses.
|
| 305 |
+
|
| 306 |
+
## Runtime configuration
|
| 307 |
+
|
| 308 |
+
Set FLUX sampler parameters through the launch script for your model and task. The bundled URDF matches the rollout camera extrinsic numbers within 1e-6, but its full SHA-256 differs from the recorded URDF fingerprint; verify full kinematics for your cell. Runtime recordings include local device identifiers, timestamps and paths; remove private metadata before sharing them.
|
flexiv-umi-infer/configs/anchor.example.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"note": "Start posture used by the robot agent. Copy to data/anchor.json and fill in your own values. Joint angles in degrees (7 per arm); gripper opening in dataset degrees (0 = closed, 90 = fully open). Keep every joint at least 0.5 deg away from the hardware limits, or the controller rejects the null-space posture.",
|
| 3 |
+
"left": [null, null, null, null, null, null, null],
|
| 4 |
+
"right": [null, null, null, null, null, null, null],
|
| 5 |
+
"left_grip": 0.0,
|
| 6 |
+
"right_grip": 0.0
|
| 7 |
+
}
|
flexiv-umi-infer/configs/cell.env.example
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Per-cell configuration. Copy to cell.env, fill in, then `set -a; source cell.env; set +a`.
|
| 2 |
+
|
| 3 |
+
# Flexiv arms (serial numbers as shown in Flexiv Elements)
|
| 4 |
+
FLEXIV_LEFT_SN=
|
| 5 |
+
FLEXIV_RIGHT_SN=
|
| 6 |
+
# Dual-arm URDF (default: urdf/flexiv_rizon4_dual_umi.urdf)
|
| 7 |
+
#FLEXIV_URDF=
|
| 8 |
+
# Joint prefix of each arm inside the URDF (default: "left_" / "right_")
|
| 9 |
+
#FLEXIV_URDF_PREFIX_LEFT=
|
| 10 |
+
#FLEXIV_URDF_PREFIX_RIGHT=
|
| 11 |
+
# Arm base translations in the shared world frame [m]
|
| 12 |
+
#FLEXIV_BASE_XYZ={"left": [0.0, -0.25, 0.0], "right": [0.0, 0.25, 0.0]}
|
| 13 |
+
# Gripper rigid points used by the tool-aware arm-to-arm distance check (URDF link names)
|
| 14 |
+
#FLEXIV_TOOL_LINKS=flange,grip_base_link,grip_camera_link,grip_tcp_link,grip_left_fingertip_link,grip_right_fingertip_link
|
| 15 |
+
|
| 16 |
+
# Insta360 wrist cameras: body serial per arm and which fisheye half faces the workspace
|
| 17 |
+
INSTA360_LEFT_SN=
|
| 18 |
+
INSTA360_RIGHT_SN=
|
| 19 |
+
INSTA360_LEFT_HALF=right
|
| 20 |
+
INSTA360_RIGHT_HALF=right
|
| 21 |
+
# Directory with the Insta360 CameraSDK shared libraries; patched CLI (see tools/README.md)
|
| 22 |
+
INSTA360_SDK_LIB=
|
| 23 |
+
#INSTA360_CLI=tools/insta360_cli_dual
|
| 24 |
+
|
| 25 |
+
# Per-cell data: anchor.json, gripper_calib.json, E_left.npy, E_right.npy, E_from_urdf.json
|
| 26 |
+
UMI_INFER_DATA=data
|
flexiv-umi-infer/data/.gitkeep
ADDED
|
File without changes
|
flexiv-umi-infer/pyproject.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "flexiv-umi-infer"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "Real-robot inference for bimanual UMI policies (pi0.5 / FLUX 3 Action) on a Flexiv Rizon4 dual-arm cell"
|
| 9 |
+
requires-python = ">=3.10"
|
| 10 |
+
license = "Apache-2.0"
|
| 11 |
+
dependencies = ["numpy", "scipy", "msgpack>=1.0", "websockets>=15,<18"]
|
| 12 |
+
|
| 13 |
+
[project.optional-dependencies]
|
| 14 |
+
# Robot PC. flexivrdk (1.9.x) and flexivdrdk come from Flexiv and are installed separately.
|
| 15 |
+
robot = ["yourdfpy", "opencv-python", "python-can", "canalystii"]
|
| 16 |
+
# GPU box, pi0.5: also install openpi-umi (pip install -e <openpi-umi>).
|
| 17 |
+
pi05 = ["opencv-python", "pandas"]
|
| 18 |
+
# GPU box, FLUX: also install flux-umi (pip install -e <flux-umi>).
|
| 19 |
+
flux = ["av", "pillow"]
|
| 20 |
+
mock = ["opencv-python", "pillow"]
|
| 21 |
+
dev = ["pytest"]
|
| 22 |
+
|
| 23 |
+
[tool.hatch.build.targets.wheel]
|
| 24 |
+
packages = ["umi_infer"]
|
flexiv-umi-infer/tests/__init__.py
ADDED
|
File without changes
|
flexiv-umi-infer/tests/conftest.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
# Fake cell identity: the tests never touch hardware or load the URDF.
|
| 4 |
+
os.environ.setdefault("FLEXIV_LEFT_SN", "TEST-LEFT")
|
| 5 |
+
os.environ.setdefault("FLEXIV_RIGHT_SN", "TEST-RIGHT")
|
| 6 |
+
os.environ.setdefault("FLEXIV_URDF", "test.urdf")
|
flexiv-umi-infer/tests/test_cloth_defaults.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI contract tests: no sockets, weights or hardware."""
|
| 2 |
+
import unittest
|
| 3 |
+
from unittest.mock import patch
|
| 4 |
+
from umi_infer import policy_server as server
|
| 5 |
+
async def no_server(*args,**kwargs):pass
|
| 6 |
+
class ClothDefaultsTest(unittest.TestCase):
|
| 7 |
+
def test_both_cli_prompts_are_folding(self):
|
| 8 |
+
with patch('sys.argv',['policy_server']),patch.object(server,'_build_policy') as build,patch.object(server,'_serve',new=no_server):
|
| 9 |
+
server.main()
|
| 10 |
+
args=build.call_args.args[0]
|
| 11 |
+
self.assertEqual(args.prompt,'fold the clothes');self.assertEqual(args.flux_prompt,'fold the clothes')
|
| 12 |
+
def test_pi05_sampling_steps_reach_adapter(self):
|
| 13 |
+
with patch('sys.argv',['policy_server','--policy','pi05','--checkpoint-dir','fixture','--num-denoise-steps','7']),patch('umi_infer.policies.umi_pi05_dual.UmiPi05DualPolicy') as adapter,patch.object(server,'_serve',new=no_server):
|
| 14 |
+
server.main()
|
| 15 |
+
self.assertEqual(adapter.call_args.kwargs['num_denoise_steps'],7)
|
| 16 |
+
self.assertEqual(adapter.call_args.kwargs['prompt'],'fold the clothes')
|
| 17 |
+
if __name__=='__main__':unittest.main()
|
flexiv-umi-infer/tests/test_flexiv_trace.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline tests for FlexivRobotIO execution logs (CSV + chunks.jsonl): fake RobotPair / reachable, no robot.
|
| 2 |
+
|
| 3 |
+
python -m pytest tests/test_flexiv_trace.py
|
| 4 |
+
"""
|
| 5 |
+
import csv
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import tempfile
|
| 9 |
+
import time
|
| 10 |
+
import unittest
|
| 11 |
+
from types import SimpleNamespace
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
from umi_infer.protocol import Action
|
| 16 |
+
from umi_infer.robot_io import flexiv as F
|
| 17 |
+
|
| 18 |
+
SIDES = ("left", "right")
|
| 19 |
+
ANCHOR = {"left": np.array([0.0, -0.4, -0.2, 1.0, 0.0, 0.0, 0.0]),
|
| 20 |
+
"right": np.array([0.0, 0.4, -0.2, 1.0, 0.0, 0.0, 0.0])}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class FakeModel:
|
| 24 |
+
"""Unreachable if |y|>0.35 in the arm base frame (right arm world y>0.6); otherwise returns seed as the solution."""
|
| 25 |
+
def reachable(self, pose, seed, _free):
|
| 26 |
+
return abs(pose[1]) < 0.35, list(seed)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class FakePair:
|
| 30 |
+
"""Measured pose = command lagging by 2mm (x)."""
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.cmd = [ANCHOR["left"].copy(), ANCHOR["right"].copy()]
|
| 33 |
+
|
| 34 |
+
def states(self):
|
| 35 |
+
out = []
|
| 36 |
+
for h in range(2):
|
| 37 |
+
p = np.array(self.cmd[h], float)
|
| 38 |
+
p[0] -= 0.002
|
| 39 |
+
out.append(SimpleNamespace(tcp_pose=p.tolist(), q=[0.1] * 7))
|
| 40 |
+
return out
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def make_io(path, **kw):
|
| 44 |
+
io = F.FlexivRobotIO(dry_run=True, record_path=path, play_scale=1.0, servo_rate_hz=200, **kw)
|
| 45 |
+
lt = io._load_lt()
|
| 46 |
+
io._pair = FakePair()
|
| 47 |
+
io._models = {s: FakeModel() for s in SIDES}
|
| 48 |
+
io._bridge = {s: np.eye(4) for s in SIDES}
|
| 49 |
+
io._bridge["left"][:3, 3] = lt.BASE_XYZ["left"]
|
| 50 |
+
io._bridge["right"][:3, 3] = lt.BASE_XYZ["right"]
|
| 51 |
+
io._anchor_w = {s: ANCHOR[s].copy() for s in SIDES}
|
| 52 |
+
io._anchor_q = {s: np.zeros(7) for s in SIDES}
|
| 53 |
+
return io
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def action(seq, n, y_end=0.4):
|
| 57 |
+
"""Right arm moves along +y to y_end (tail unreachable beyond 0.6); left arm still. xyzw."""
|
| 58 |
+
traj = {"left": [[0.0, -0.4, -0.2, 0, 0, 0, 1]] * n,
|
| 59 |
+
"right": [[0.0, 0.4 + (y_end - 0.4) * i / (n - 1), -0.2, 0, 0, 0, 1]
|
| 60 |
+
for i in range(n)]}
|
| 61 |
+
return Action(seq=seq, stamp=time.time(), control="eef_pose",
|
| 62 |
+
eef_target={s: traj[s][0] for s in SIDES}, gripper={s: 0.0 for s in SIDES},
|
| 63 |
+
eef_traj=traj, gripper_traj={s: [0.0] * n for s in SIDES}, dt=1 / 30,
|
| 64 |
+
extra={"policy": "flux"})
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TraceTest(unittest.TestCase):
|
| 68 |
+
def test_csv_and_chunks(self):
|
| 69 |
+
d = tempfile.mkdtemp()
|
| 70 |
+
path = os.path.join(d, "live.csv")
|
| 71 |
+
io = make_io(path)
|
| 72 |
+
# Only the recording part of start(); the rest needs a real robot
|
| 73 |
+
io._rec = open(path, "w", newline="", buffering=1)
|
| 74 |
+
cols = ["t", "seq", "idx", "phase"]
|
| 75 |
+
for s in SIDES:
|
| 76 |
+
cols += ["%s_cmd_%s" % (s, a) for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
|
| 77 |
+
cols += ["%s_act_%s" % (s, a) for a in ("x", "y", "z")]
|
| 78 |
+
cols += ["%s_grip_cmd" % s, "%s_grip_meas" % s]
|
| 79 |
+
cols += ["pair_dist_m"] + ["%s_act_%s" % (s, a) for s in SIDES
|
| 80 |
+
for a in ("qw", "qx", "qy", "qz")]
|
| 81 |
+
cols += ["%s_q%d" % (s, k) for s in SIDES for k in range(1, 8)] + ["knot"]
|
| 82 |
+
cols += ["%s_ext%s_%s" % (s, fr, a) for s in SIDES for fr in ("w", "tcp")
|
| 83 |
+
for a in ("fx", "fy", "fz", "mx", "my", "mz")]
|
| 84 |
+
io._rec_w = csv.writer(io._rec)
|
| 85 |
+
io._rec_w.writerow(cols)
|
| 86 |
+
io._trace = open(F.trace_path(path), "w", buffering=1)
|
| 87 |
+
pose0 = np.stack([io._anchor_w[s] for s in SIDES])
|
| 88 |
+
io._buf = F._Buf(pose_w=pose0[None], twist=np.zeros((1, 2, 6)), grip=np.zeros((1, 2)),
|
| 89 |
+
dt=0.01, start=time.perf_counter(), seq=-1)
|
| 90 |
+
io._last_cmd_w = pose0.copy()
|
| 91 |
+
|
| 92 |
+
io.apply_action(action(1, 6)) # all pass
|
| 93 |
+
import threading
|
| 94 |
+
th = threading.Thread(target=io._servo_loop, daemon=True)
|
| 95 |
+
th.start()
|
| 96 |
+
time.sleep(6 / 30 + F.HOLD_ROW_S + 0.2) # play out + hold rows
|
| 97 |
+
io.apply_action(action(2, 10, y_end=0.7)) # tail unreachable -> truncated
|
| 98 |
+
time.sleep(0.4)
|
| 99 |
+
io._stop_ev.set()
|
| 100 |
+
th.join(2)
|
| 101 |
+
io._rec.close()
|
| 102 |
+
io._trace.close()
|
| 103 |
+
|
| 104 |
+
with open(F.trace_path(path)) as f:
|
| 105 |
+
recs = [json.loads(ln) for ln in f]
|
| 106 |
+
c1, c2 = [r for r in recs if r.get("event") == "chunk"]
|
| 107 |
+
self.assertEqual((c1["status"], c1["keep"], c1["n_model"]), ("ok", 6, 6))
|
| 108 |
+
self.assertEqual(c2["status"], "truncated")
|
| 109 |
+
self.assertLess(c2["keep"], 10)
|
| 110 |
+
self.assertTrue(c2["why"].startswith("IK: sampled"))
|
| 111 |
+
self.assertIn(False, c2["ik"]["right"]["ok"])
|
| 112 |
+
self.assertEqual(len(c1["model"]["right"]), 6)
|
| 113 |
+
self.assertEqual(c1["ik"]["left"]["q"][0], [0.0] * 7)
|
| 114 |
+
|
| 115 |
+
with open(path, newline="") as f:
|
| 116 |
+
rows = list(csv.DictReader(f))
|
| 117 |
+
ph = [(int(r["seq"]), r["phase"]) for r in rows]
|
| 118 |
+
self.assertIn((1, "hold"), ph)
|
| 119 |
+
self.assertEqual(sorted({int(r["idx"]) for r in rows if r["seq"] == "1"}),
|
| 120 |
+
list(range(6)))
|
| 121 |
+
r = rows[-1]
|
| 122 |
+
self.assertAlmostEqual(float(r["left_cmd_x"]) - float(r["left_act_x"]), 0.002, 5)
|
| 123 |
+
self.assertEqual(r["right_act_qw"], "1.00000")
|
| 124 |
+
self.assertEqual(r["right_q7"], "0.10000")
|
| 125 |
+
self.assertNotIn(None, r) # column count matches header
|
| 126 |
+
self.assertIn((1, "wait"), ph) # cycles waiting for the next chunk are tagged
|
| 127 |
+
n1 = sum(1 for x in rows if x["seq"] == "1" and x["phase"] == "run")
|
| 128 |
+
self.assertGreater(n1, 6 * 3) # one row per servo cycle, not per step
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class FeedforwardTest(unittest.TestCase):
|
| 132 |
+
def test_end_velocity_zero_and_interpolated(self):
|
| 133 |
+
io = make_io(None)
|
| 134 |
+
pw = np.zeros((5, 2, 7)); pw[..., 3] = 1.0
|
| 135 |
+
pw[:, :, 0] = np.arange(5)[:, None] * 0.01 # constant 10mm/step along x
|
| 136 |
+
tw = io._twists(pw, 0.1)
|
| 137 |
+
np.testing.assert_allclose(tw[-1], 0.0) # last step = stop
|
| 138 |
+
self.assertGreater(tw[2, 0, 0], 0.0)
|
| 139 |
+
buf = F._Buf(pose_w=pw, twist=tw, grip=np.zeros((5, 2)), dt=0.1, start=0.0, seq=1)
|
| 140 |
+
np.testing.assert_allclose(io._ff_twist(buf, 1.5), (tw[1] + tw[2]) / 2) # interpolated between steps
|
| 141 |
+
np.testing.assert_allclose(io._ff_twist(buf, 4.0), 0.0) # finished
|
| 142 |
+
np.testing.assert_allclose(io._ff_twist(buf, 9.0), 0.0) # hold after finish (awaiting inference)
|
| 143 |
+
|
| 144 |
+
def test_nullspace_weight_range(self):
|
| 145 |
+
self.assertEqual(make_io(None, nullspace_weight=1.0).ns_weight, 1.0)
|
| 146 |
+
with self.assertRaises(ValueError):
|
| 147 |
+
make_io(None, nullspace_weight=2.0)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class StepLimitTest(unittest.TestCase):
|
| 151 |
+
def test_first_and_later_chunk_step_limits(self):
|
| 152 |
+
io = make_io(None, first_steps=4, steps=7)
|
| 153 |
+
io._buf = F._Buf(pose_w=np.zeros((1, 2, 7)), twist=np.zeros((1, 2, 6)), grip=np.zeros((1, 2)),
|
| 154 |
+
dt=0.01, start=time.perf_counter(), seq=-1)
|
| 155 |
+
io._last_cmd_w = np.stack([ANCHOR[s] for s in SIDES])
|
| 156 |
+
io.apply_action(action(1, 10, y_end=0.45))
|
| 157 |
+
self.assertEqual(len(io._buf.pose_w), 4) # first chunk: 4 steps
|
| 158 |
+
io.apply_action(action(2, 10, y_end=0.45))
|
| 159 |
+
self.assertEqual(len(io._buf.pose_w), 7) # later chunks: 7 steps
|
| 160 |
+
io.apply_action(action(3, 5, y_end=0.45))
|
| 161 |
+
self.assertEqual(len(io._buf.pose_w), 5) # fewer than the cap: run all
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
unittest.main()
|
flexiv-umi-infer/tests/test_flux_action_dual.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only checks for the FLUX UMI bridge; no weights, GPU or robot IO."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import unittest
|
| 7 |
+
from types import SimpleNamespace
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import websockets
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
from flux_action.config import PolicyConfig
|
| 15 |
+
from flux_action.data.umi.representation import make_window, quaternion_matrix, relative_hand
|
| 16 |
+
from umi_infer.policies.flux_action_dual import (FluxActionDualPolicy, _extrinsic,
|
| 17 |
+
_pose_matrix, decode_image, decode_targets,
|
| 18 |
+
encode_state, validate_extrinsics)
|
| 19 |
+
from umi_infer.policy_server import _build_policy, _handle
|
| 20 |
+
from umi_infer.protocol import CameraFrame, Observation, pack, unpack_action
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class FakeModel(torch.nn.Module):
|
| 24 |
+
def __init__(self):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.register_buffer("placement", torch.empty(0))
|
| 27 |
+
bounds = {"q01": [-10.0] * 20, "q99": [10.0] * 20}
|
| 28 |
+
self.config = PolicyConfig(action_dim=20, chunk_size=32, fps=30,
|
| 29 |
+
camera_layout="side_by_side", camera_keys=list((
|
| 30 |
+
"images.left_ego", "images.right_ego")),
|
| 31 |
+
canvas_hw=[256, 512], gripper_flip_dims=[],
|
| 32 |
+
state_normalization=bounds, action_normalization=bounds)
|
| 33 |
+
self.reset_count = 0
|
| 34 |
+
self.last_batch = None
|
| 35 |
+
self.output = torch.zeros(1, 32, 20)
|
| 36 |
+
for offset in (0, 10):
|
| 37 |
+
self.output[0, :, offset + 3] = 1
|
| 38 |
+
self.output[0, :, offset + 7] = 1
|
| 39 |
+
self.output[0, :, offset + 9] = 42 + offset
|
| 40 |
+
self.output[0, :, 0] = 0.01
|
| 41 |
+
self.output[0, :, 10] = -0.02
|
| 42 |
+
|
| 43 |
+
def reset(self):
|
| 44 |
+
self.reset_count += 1
|
| 45 |
+
|
| 46 |
+
def predict_action_chunk(self, batch):
|
| 47 |
+
self.last_batch = batch
|
| 48 |
+
return self.output
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def frame(name, rgb):
|
| 52 |
+
image = Image.new("RGB", (40, 40), rgb)
|
| 53 |
+
data = io.BytesIO()
|
| 54 |
+
image.save(data, format="JPEG", quality=100)
|
| 55 |
+
return CameraFrame(name=name, format="jpeg", width=40, height=40, data=data.getvalue())
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def observation():
|
| 59 |
+
return Observation(seq=17, stamp=1.0,
|
| 60 |
+
images={"left_wrist": frame("left_wrist", (240, 10, 10)),
|
| 61 |
+
"right_wrist": frame("right_wrist", (10, 10, 240))},
|
| 62 |
+
eef={"left": [0.1, 0.2, 0.3, 0, 0, 0, 1],
|
| 63 |
+
"right": [-0.1, 0.2, 0.3, 0, 0, 0, 1]},
|
| 64 |
+
eef_prev={"left": [0.09, 0.2, 0.3, 0, 0, 0, 1],
|
| 65 |
+
"right": [-0.1, 0.2, 0.3, 0, 0, 0, 1]},
|
| 66 |
+
gripper={"left": 31.5, "right": 90.0})
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class GeometryTests(unittest.TestCase):
|
| 70 |
+
def test_training_state_and_inverse_with_nontrivial_rotation(self):
|
| 71 |
+
# xyzw on the wire, wxyz in FLUX's source states.
|
| 72 |
+
cur = np.array([0.4, -0.2, 0.8, 0.0, 0.0, 0.38268343, 0.92387953])
|
| 73 |
+
prev = np.array([0.39, -0.24, 0.81, 0.1, 0.0, 0.0, 0.99498744])
|
| 74 |
+
cur_train = np.r_[cur[:3], cur[6], cur[3:6], 15.0]
|
| 75 |
+
prev_train = np.r_[prev[:3], prev[6], prev[3:6], 8.0]
|
| 76 |
+
expected = relative_hand(cur_train, prev_train)
|
| 77 |
+
state, anchor = encode_state(cur, prev, 15.0, np.eye(4))
|
| 78 |
+
expected[-1] = 15.0
|
| 79 |
+
np.testing.assert_allclose(state, expected, atol=1e-6)
|
| 80 |
+
future = np.r_[[0.43, -0.19, 0.81], [0, 0.25881905, 0, 0.96592583], 62.0]
|
| 81 |
+
relative = relative_hand(cur_train, np.r_[future[:3], future[6], future[3:6], future[7]])
|
| 82 |
+
poses, grippers = decode_targets(anchor, relative[None], np.eye(4))
|
| 83 |
+
np.testing.assert_allclose(_pose_matrix(poses[0]), _pose_matrix(future[:7]), atol=1e-6)
|
| 84 |
+
self.assertAlmostEqual(grippers[0], 62.0)
|
| 85 |
+
|
| 86 |
+
def test_extrinsic_is_symmetric_and_rejects_nonrigid(self):
|
| 87 |
+
import tempfile
|
| 88 |
+
from pathlib import Path
|
| 89 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 90 |
+
path = Path(temp) / "E.npy"
|
| 91 |
+
e = np.eye(4)
|
| 92 |
+
e[:3, 3] = [0.04, -0.01, 0.02]
|
| 93 |
+
np.save(path, e)
|
| 94 |
+
loaded = _extrinsic(path)
|
| 95 |
+
cur = [0, 0, 0, 0, 0, 0, 1]
|
| 96 |
+
_, anchor = encode_state(cur, cur, 1.0, np.linalg.inv(loaded))
|
| 97 |
+
relative = np.array([[0, 0, 0, 1, 0, 0, 0, 1, 0, 1]])
|
| 98 |
+
poses, _ = decode_targets(anchor, relative, loaded)
|
| 99 |
+
np.testing.assert_allclose(_pose_matrix(poses[0]), np.eye(4), atol=1e-6)
|
| 100 |
+
e[0, 0] = 2
|
| 101 |
+
np.save(path, e)
|
| 102 |
+
with self.assertRaises(ValueError):
|
| 103 |
+
_extrinsic(path)
|
| 104 |
+
|
| 105 |
+
def test_reject_bad_inputs(self):
|
| 106 |
+
with self.assertRaises(ValueError):
|
| 107 |
+
_pose_matrix([0, 0, 0, 0, 0, 0, 0])
|
| 108 |
+
with self.assertRaises(ValueError):
|
| 109 |
+
_pose_matrix([1e100, 0, 0, 0, 0, 0, 1])
|
| 110 |
+
with self.assertRaises(ValueError):
|
| 111 |
+
decode_targets(np.eye(4), [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], np.eye(4))
|
| 112 |
+
with self.assertRaises(ValueError):
|
| 113 |
+
decode_image(CameraFrame(name="x", format="jpeg", width=4, height=4, data=b"bad"))
|
| 114 |
+
|
| 115 |
+
def test_urdf_extrinsics_need_both_sides_and_matching_provenance(self):
|
| 116 |
+
import tempfile
|
| 117 |
+
from pathlib import Path
|
| 118 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 119 |
+
root = Path(temp)
|
| 120 |
+
urdf = root / "robot.urdf"
|
| 121 |
+
urdf.write_text("<robot/>")
|
| 122 |
+
matrices = {}
|
| 123 |
+
for side, shift in (("left", -0.07), ("right", 0.04)):
|
| 124 |
+
e = np.eye(4)
|
| 125 |
+
e[:3, :3] = quaternion_matrix([np.cos(np.pi / 4), 0, np.sin(np.pi / 4), 0])
|
| 126 |
+
e[:3, 3] = [shift, 0.03, -0.02]
|
| 127 |
+
np.save(root / f"E_{side}.npy", e)
|
| 128 |
+
matrices[side] = e
|
| 129 |
+
provenance = root / "E_from_urdf.json"
|
| 130 |
+
record = {"urdf": str(urdf), "camera_pose_source": "cad",
|
| 131 |
+
"sides": {side: {"npy": str(root / f"E_{side}.npy"),
|
| 132 |
+
"E_T_cam_flange": matrices[side].tolist()}
|
| 133 |
+
for side in ("left", "right")}}
|
| 134 |
+
provenance.write_text(json.dumps(record))
|
| 135 |
+
loaded = validate_extrinsics(root / "E_left.npy", root / "E_right.npy", provenance)
|
| 136 |
+
np.testing.assert_allclose(loaded["left"], matrices["left"])
|
| 137 |
+
with self.assertRaisesRegex(ValueError, "E_LEFT and E_RIGHT"):
|
| 138 |
+
validate_extrinsics(None, root / "E_right.npy", provenance)
|
| 139 |
+
with self.assertRaisesRegex(ValueError, "right E path"):
|
| 140 |
+
validate_extrinsics(root / "E_left.npy", root / "E_left.npy", provenance)
|
| 141 |
+
bad = matrices["right"].copy()
|
| 142 |
+
bad[0, 3] += 0.01
|
| 143 |
+
np.save(root / "E_right.npy", bad)
|
| 144 |
+
with self.assertRaisesRegex(ValueError, "right E differs"):
|
| 145 |
+
validate_extrinsics(root / "E_left.npy", root / "E_right.npy", provenance)
|
| 146 |
+
import os
|
| 147 |
+
before = urdf.stat().st_mtime_ns
|
| 148 |
+
os.utime(urdf, ns=(before, provenance.stat().st_mtime_ns + 1_000_000_000))
|
| 149 |
+
with self.assertRaisesRegex(ValueError, "older than"):
|
| 150 |
+
validate_extrinsics(root / "E_left.npy", root / "E_right.npy", provenance)
|
| 151 |
+
|
| 152 |
+
def test_training_window_roundtrip_through_both_flange_extrinsics(self):
|
| 153 |
+
states = np.zeros((35, 16), dtype=np.float32)
|
| 154 |
+
for hand in range(2):
|
| 155 |
+
base = hand * 8
|
| 156 |
+
states[:, base:base + 3] = (np.arange(35)[:, None] * [0.002, -0.001, 0.004]
|
| 157 |
+
+ [hand * 0.2, 0.3, 0.4])
|
| 158 |
+
angles = np.arange(35) * (0.01 if hand == 0 else -0.018)
|
| 159 |
+
states[:, base + 3] = np.cos(angles / 2)
|
| 160 |
+
states[:, base + 6] = np.sin(angles / 2)
|
| 161 |
+
states[:, base + 7] = np.arange(35) * 0.1 + hand
|
| 162 |
+
expected_state, expected_actions = make_window(states, 1)
|
| 163 |
+
for hand in range(2):
|
| 164 |
+
base = hand * 8
|
| 165 |
+
offset = hand * 10
|
| 166 |
+
e = np.eye(4)
|
| 167 |
+
e[:3, :3] = quaternion_matrix([0.96, 0.1, 0.25, -0.07])
|
| 168 |
+
e[:3, 3] = [0.07, -0.04, 0.03]
|
| 169 |
+
def flange(row):
|
| 170 |
+
cam = np.eye(4)
|
| 171 |
+
cam[:3, :3] = quaternion_matrix(row[3:7])
|
| 172 |
+
cam[:3, 3] = row[:3]
|
| 173 |
+
flange_pose = cam @ e
|
| 174 |
+
from umi_infer.policies.flux_action_dual import _matrix_pose
|
| 175 |
+
return _matrix_pose(flange_pose)
|
| 176 |
+
state, anchor = encode_state(flange(states[1, base:base + 8]),
|
| 177 |
+
flange(states[0, base:base + 8]),
|
| 178 |
+
states[1, base + 7], np.linalg.inv(e))
|
| 179 |
+
np.testing.assert_allclose(state, expected_state[offset:offset + 10], atol=1e-6)
|
| 180 |
+
poses, grippers = decode_targets(anchor,
|
| 181 |
+
expected_actions[:, offset:offset + 10], e)
|
| 182 |
+
np.testing.assert_allclose(grippers, states[2:34, base + 7], atol=1e-6)
|
| 183 |
+
for index in range(32):
|
| 184 |
+
np.testing.assert_allclose(_pose_matrix(poses[index]),
|
| 185 |
+
_pose_matrix(flange(states[index + 2, base:base + 8])),
|
| 186 |
+
atol=1e-6)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class PolicyTests(unittest.TestCase):
|
| 190 |
+
def make_policy(self):
|
| 191 |
+
import tempfile
|
| 192 |
+
from pathlib import Path
|
| 193 |
+
fake = FakeModel()
|
| 194 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 195 |
+
identity = Path(temp) / "identity.npy"
|
| 196 |
+
np.save(identity, np.eye(4))
|
| 197 |
+
policy = FluxActionDualPolicy(export_dir="unused", source_dir="unused", device="cpu",
|
| 198 |
+
action_horizon=3, model=fake,
|
| 199 |
+
extrinsics={"left": identity, "right": identity})
|
| 200 |
+
return policy, fake
|
| 201 |
+
|
| 202 |
+
def test_missing_extrinsics_rejected_even_when_bypassing_startup(self):
|
| 203 |
+
import tempfile
|
| 204 |
+
from pathlib import Path
|
| 205 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 206 |
+
identity = Path(temp) / "identity.npy"
|
| 207 |
+
np.save(identity, np.eye(4))
|
| 208 |
+
for extrinsics in (None, {"left": identity}, {"right": identity}):
|
| 209 |
+
with self.subTest(extrinsics=extrinsics):
|
| 210 |
+
with self.assertRaisesRegex(ValueError, "E_LEFT and E_RIGHT"):
|
| 211 |
+
FluxActionDualPolicy(export_dir="unused", source_dir="unused",
|
| 212 |
+
device="cpu", model=FakeModel(),
|
| 213 |
+
extrinsics=extrinsics)
|
| 214 |
+
|
| 215 |
+
def test_image_state_and_action(self):
|
| 216 |
+
policy, fake = self.make_policy()
|
| 217 |
+
action = policy.infer(observation())
|
| 218 |
+
self.assertEqual(action.seq, 17)
|
| 219 |
+
self.assertAlmostEqual(action.dt, 1 / 30)
|
| 220 |
+
self.assertEqual(len(action.eef_traj["left"]), 3)
|
| 221 |
+
self.assertEqual(len(action.eef_traj["right"]), 3)
|
| 222 |
+
self.assertAlmostEqual(action.eef_traj["left"][0][0], 0.11, places=5)
|
| 223 |
+
self.assertAlmostEqual(action.eef_traj["right"][0][0], -0.12, places=5)
|
| 224 |
+
self.assertAlmostEqual(action.gripper_traj["left"][0], 42)
|
| 225 |
+
self.assertAlmostEqual(action.gripper_traj["right"][0], 52)
|
| 226 |
+
self.assertEqual(fake.last_batch["state"].shape, (1, 20))
|
| 227 |
+
self.assertAlmostEqual(fake.last_batch["state"][0, 9].item(), 31.5)
|
| 228 |
+
self.assertAlmostEqual(fake.last_batch["state"][0, 19].item(), 90)
|
| 229 |
+
left = fake.last_batch["images.left_ego"]
|
| 230 |
+
right = fake.last_batch["images.right_ego"]
|
| 231 |
+
self.assertEqual(left.shape, (1, 3, 256, 256))
|
| 232 |
+
self.assertGreater(left[0, 0, 10, 10], left[0, 2, 10, 10])
|
| 233 |
+
self.assertGreater(right[0, 2, 10, 10], right[0, 0, 10, 10])
|
| 234 |
+
self.assertEqual(unpack_action(pack(action)).eef_traj, action.eef_traj)
|
| 235 |
+
self.assertEqual(fake.last_batch["task"], ["fold the clothes"])
|
| 236 |
+
|
| 237 |
+
def test_missing_camera_and_nan_output_rejected(self):
|
| 238 |
+
policy, fake = self.make_policy()
|
| 239 |
+
obs = observation()
|
| 240 |
+
obs.images.pop("right_wrist")
|
| 241 |
+
with self.assertRaises(ValueError):
|
| 242 |
+
policy.infer(obs)
|
| 243 |
+
fake.output[0, 0, 0] = float("nan")
|
| 244 |
+
with self.assertRaises(ValueError):
|
| 245 |
+
policy.infer(observation())
|
| 246 |
+
|
| 247 |
+
def test_previous_pose_fallback_is_explicit(self):
|
| 248 |
+
policy, fake = self.make_policy()
|
| 249 |
+
obs = observation()
|
| 250 |
+
obs.eef_prev = {}
|
| 251 |
+
action = policy.infer(obs)
|
| 252 |
+
self.assertEqual(action.extra["prev_src"], {"left": "current", "right": "current"})
|
| 253 |
+
self.assertAlmostEqual(fake.last_batch["state"][0, 0].item(), 0, places=6)
|
| 254 |
+
|
| 255 |
+
def test_old_mock_factory_unchanged(self):
|
| 256 |
+
args = SimpleNamespace(policy="mock", chunk_size=None, chunk_dt=None, policy_mode="hold")
|
| 257 |
+
self.assertEqual(type(_build_policy(args)).__name__, "MockPolicy")
|
| 258 |
+
args.policy = "flux"
|
| 259 |
+
args.flux_export = None
|
| 260 |
+
with self.assertRaises(SystemExit):
|
| 261 |
+
_build_policy(args)
|
| 262 |
+
|
| 263 |
+
def test_mock_websocket_roundtrip_without_robot(self):
|
| 264 |
+
async def run():
|
| 265 |
+
policy, fake = self.make_policy()
|
| 266 |
+
async with websockets.serve(lambda ws: _handle(ws, policy), "127.0.0.1", 0) as server:
|
| 267 |
+
port = server.sockets[0].getsockname()[1]
|
| 268 |
+
async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
|
| 269 |
+
await ws.send(pack(observation()))
|
| 270 |
+
action = unpack_action(await ws.recv())
|
| 271 |
+
self.assertEqual(action.seq, 17)
|
| 272 |
+
self.assertEqual(len(action.eef_traj["right"]), 3)
|
| 273 |
+
self.assertGreater(fake.reset_count, 1)
|
| 274 |
+
asyncio.run(run())
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
if __name__ == "__main__":
|
| 278 |
+
unittest.main()
|
flexiv-umi-infer/tests/test_rollout_rec.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline tests for the per-frame rollout recorder (robot_io/rollout_rec.py): fake RobotPair / cameras, no robot.
|
| 2 |
+
|
| 3 |
+
python -m pytest tests/test_rollout_rec.py
|
| 4 |
+
"""
|
| 5 |
+
import csv
|
| 6 |
+
import glob
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import tempfile
|
| 10 |
+
import time
|
| 11 |
+
import unittest
|
| 12 |
+
from types import SimpleNamespace
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from umi_infer.robot_io import flexiv as F
|
| 17 |
+
from umi_infer.robot_io import rollout_rec as R
|
| 18 |
+
from tests.test_flexiv_trace import ANCHOR, FakeModel, action
|
| 19 |
+
|
| 20 |
+
SIDES = ("left", "right")
|
| 21 |
+
Q_LEFT = np.radians([10.0, 20.0, 0.0, 90.0, 169.5, 60.0, 0.0]) # j5 only 0.5 deg from its 170 deg limit
|
| 22 |
+
Q_RIGHT = np.radians([0.0] * 7)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class FakePairFull:
|
| 26 |
+
"""Measured = command (x lags 2mm); provides info / actions / torque and wrench fields."""
|
| 27 |
+
def __init__(self):
|
| 28 |
+
self.cmd = [ANCHOR["left"].copy(), ANCHOR["right"].copy()]
|
| 29 |
+
|
| 30 |
+
def states(self):
|
| 31 |
+
out = []
|
| 32 |
+
for h, q in enumerate((Q_LEFT, Q_RIGHT)):
|
| 33 |
+
p = np.array(self.cmd[h], float)
|
| 34 |
+
p[0] -= 0.002
|
| 35 |
+
out.append(SimpleNamespace(tcp_pose=p.tolist(), q=q.tolist(), dq=[0.0] * 7,
|
| 36 |
+
tau=[1.0] * 7, tau_ext=[0.1] * 7,
|
| 37 |
+
ext_wrench_in_world=[1, 2, 3, 0.1, 0.2, 0.3],
|
| 38 |
+
ext_wrench_in_tcp=[3, 2, 1, 0.3, 0.2, 0.1]))
|
| 39 |
+
return out
|
| 40 |
+
|
| 41 |
+
def actions(self):
|
| 42 |
+
return [SimpleNamespace(tcp_pose_d=list(self.cmd[h]), q_d=q.tolist())
|
| 43 |
+
for h, q in enumerate((Q_LEFT, Q_RIGHT))]
|
| 44 |
+
|
| 45 |
+
def info(self):
|
| 46 |
+
lim = np.radians(F.RQMAX)
|
| 47 |
+
return [SimpleNamespace(q_min=(-lim).tolist(), q_max=lim.tolist(),
|
| 48 |
+
K_x_nom=[10000.0] * 3 + [1500.0] * 3) for _ in range(2)]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class FakeDual:
|
| 52 |
+
"""yuv420p native half: (H*3/2, W) I420 planes (downsized here), stamp increases per call."""
|
| 53 |
+
def __init__(self):
|
| 54 |
+
self.n = 0
|
| 55 |
+
|
| 56 |
+
def get_frame(self, side):
|
| 57 |
+
self.n += 1
|
| 58 |
+
return np.full((96 * 3 // 2, 96), 128, np.uint8), time.time() + self.n * 1e-6
|
| 59 |
+
|
| 60 |
+
def stop(self):
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class RolloutTest(unittest.TestCase):
|
| 65 |
+
def test_full_path(self):
|
| 66 |
+
root = tempfile.mkdtemp()
|
| 67 |
+
io = F.FlexivRobotIO(dry_run=True, play_scale=1.0, servo_rate_hz=200,
|
| 68 |
+
cam_format="yuv420p", rollout_root=root, rollout_cam_hz=20)
|
| 69 |
+
lt = io._load_lt()
|
| 70 |
+
io._pair = FakePairFull()
|
| 71 |
+
io._models = {s: FakeModel() for s in SIDES}
|
| 72 |
+
io._bridge = {s: np.eye(4) for s in SIDES}
|
| 73 |
+
io._bridge["left"][:3, 3] = lt.BASE_XYZ["left"]
|
| 74 |
+
io._bridge["right"][:3, 3] = lt.BASE_XYZ["right"]
|
| 75 |
+
io._anchor_w = {s: ANCHOR[s].copy() for s in SIDES}
|
| 76 |
+
io._anchor_q = {s: np.zeros(7) for s in SIDES}
|
| 77 |
+
io._dual = FakeDual()
|
| 78 |
+
io._open_rollout() # the same call start() makes
|
| 79 |
+
self.assertIsNotNone(io._rollout)
|
| 80 |
+
d = io._rollout.dir
|
| 81 |
+
pose0 = np.stack([io._anchor_w[s] for s in SIDES])
|
| 82 |
+
io._buf = F._Buf(pose_w=pose0[None], twist=np.zeros((1, 2, 6)), grip=np.zeros((1, 2)),
|
| 83 |
+
dt=0.01, start=time.perf_counter(), seq=-1)
|
| 84 |
+
io._last_cmd_w = pose0.copy()
|
| 85 |
+
|
| 86 |
+
import threading
|
| 87 |
+
io._servo = threading.Thread(target=io._servo_loop, daemon=True)
|
| 88 |
+
io._servo.start()
|
| 89 |
+
time.sleep(0.1)
|
| 90 |
+
obs = io.get_observation()
|
| 91 |
+
io.apply_action(action(obs.seq, 6))
|
| 92 |
+
time.sleep(6 / 30 + F.HOLD_ROW_S + 0.2)
|
| 93 |
+
io.stop()
|
| 94 |
+
|
| 95 |
+
with open(os.path.join(d, "servo.csv"), newline="") as f:
|
| 96 |
+
rows = list(csv.DictReader(f))
|
| 97 |
+
self.assertGreater(len(rows), 20)
|
| 98 |
+
with open(os.path.join(d, "servo.csv"), newline="") as f:
|
| 99 |
+
self.assertEqual(next(csv.reader(f)), R.servo_columns())
|
| 100 |
+
self.assertNotIn(None, rows[-1]) # column count matches header
|
| 101 |
+
r = rows[-1]
|
| 102 |
+
self.assertEqual(r["left_at_limit"], "1")
|
| 103 |
+
self.assertEqual(r["left_margin_joint"], "5")
|
| 104 |
+
self.assertAlmostEqual(float(r["left_margin_min"]), 0.5, 2)
|
| 105 |
+
self.assertEqual(r["right_at_limit"], "0")
|
| 106 |
+
self.assertAlmostEqual(float(r["left_q_d5"]), 169.5, 2) # controller desired joint
|
| 107 |
+
self.assertAlmostEqual(float(r["left_pos_err_mm"]), 2.0, 2)
|
| 108 |
+
self.assertEqual(r["left_extw_mz"], "0.3")
|
| 109 |
+
self.assertIn("run", {x["phase"] for x in rows})
|
| 110 |
+
self.assertIn("1", {x["seq"] for x in rows})
|
| 111 |
+
|
| 112 |
+
with open(os.path.join(d, "events.jsonl")) as f:
|
| 113 |
+
ev = [json.loads(ln) for ln in f]
|
| 114 |
+
kinds = {e["event"] for e in ev}
|
| 115 |
+
self.assertTrue({"obs", "chunk", "stop"} <= kinds, kinds)
|
| 116 |
+
ob = next(e for e in ev if e["event"] == "obs")
|
| 117 |
+
self.assertIn("eef_prev", ob)
|
| 118 |
+
self.assertTrue(glob.glob(os.path.join(d, "obs", "*.jpg"))) # model input images
|
| 119 |
+
for s in SIDES:
|
| 120 |
+
self.assertTrue(glob.glob(os.path.join(d, "cams", s, "*.jpg")), s) # live frames
|
| 121 |
+
with open(os.path.join(d, "meta.json")) as f:
|
| 122 |
+
meta = json.load(f)
|
| 123 |
+
self.assertEqual(meta["K_x"]["left"][3], 1500.0 * io.kx_ratio)
|
| 124 |
+
self.assertAlmostEqual(meta["q_max_deg"]["left"][4], 170.0, 4)
|
| 125 |
+
with open(os.path.join(d, "summary.json")) as f:
|
| 126 |
+
sm = json.load(f)
|
| 127 |
+
self.assertEqual(sm["dropped"], 0)
|
| 128 |
+
self.assertEqual(sm["arms"]["left"]["joint"], 5)
|
| 129 |
+
self.assertGreater(sm["arms"]["left"]["limit_frac"], 0.9)
|
| 130 |
+
self.assertEqual(sm["arms"]["right"]["limit_frac"], 0.0)
|
| 131 |
+
|
| 132 |
+
def test_disabled(self):
|
| 133 |
+
io = F.FlexivRobotIO(dry_run=True, rollout_root=None)
|
| 134 |
+
io._open_rollout()
|
| 135 |
+
self.assertIsNone(io._rollout)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
unittest.main()
|
flexiv-umi-infer/tools/README.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 中文 / English
|
| 2 |
+
|
| 3 |
+
[中文](#zh) · [English](#en)
|
| 4 |
+
|
| 5 |
+
<a id="zh"></a>
|
| 6 |
+
|
| 7 |
+
# insta360_cli_dual
|
| 8 |
+
|
| 9 |
+
基于Linux版Insta360 CameraSDK的非交互CLI。机器人IO使用`discover`和`stream`读取每台腕相机的实时H.264。
|
| 10 |
+
|
| 11 |
+
- `--service-port=<N>`在Open之前调用`Camera::SetServicePort(N)`。每个进程使用不同端口,否则第二台相机可能无法发现。
|
| 12 |
+
- `INSTA360_VIDEO0_PATH`、`INSTA360_VIDEO1_PATH`指定视频流输出路径,可使用FIFO;每个数据包立即刷新。
|
| 13 |
+
|
| 14 |
+
## 构建
|
| 15 |
+
|
| 16 |
+
CameraSDK需向Insta360另行获取,解压后运行:
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
SDK=/path/to/CameraSDK-<version>-Linux
|
| 20 |
+
g++ -std=c++17 -O2 -I$SDK/include tools/insta360_cli_dual.cc \
|
| 21 |
+
-L$SDK/lib -lCameraSDK -lpthread -Wl,-rpath,$SDK/lib -o tools/insta360_cli_dual
|
| 22 |
+
export INSTA360_SDK_LIB=$SDK/lib
|
| 23 |
+
tools/insta360_cli_dual discover # prints the serials of connected cameras as JSON
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
将相机USB模式设为Android(手机控制),安装SDK提供的udev规则,以便无需root即可访问设备。
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+
<a id="en"></a>
|
| 31 |
+
|
| 32 |
+
# insta360_cli_dual
|
| 33 |
+
|
| 34 |
+
A small non-interactive CLI around the Insta360 CameraSDK (Linux). The robot IO uses its `discover` and
|
| 35 |
+
`stream` commands to pull live H.264 from each wrist camera.
|
| 36 |
+
|
| 37 |
+
Two additions make two cameras stream at once into ffmpeg:
|
| 38 |
+
|
| 39 |
+
- `--service-port=<N>` calls `Camera::SetServicePort(N)` before `Open()`. Each process needs its own port,
|
| 40 |
+
otherwise the second camera is not found.
|
| 41 |
+
- `INSTA360_VIDEO0_PATH` / `INSTA360_VIDEO1_PATH` set the output file of each video stream. Point them
|
| 42 |
+
at a fifo for real-time streaming; every packet is flushed.
|
| 43 |
+
|
| 44 |
+
## Build
|
| 45 |
+
|
| 46 |
+
The CameraSDK is not included. Request it from Insta360 and unpack it, then:
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
SDK=/path/to/CameraSDK-<version>-Linux
|
| 50 |
+
g++ -std=c++17 -O2 -I$SDK/include tools/insta360_cli_dual.cc \
|
| 51 |
+
-L$SDK/lib -lCameraSDK -lpthread -Wl,-rpath,$SDK/lib -o tools/insta360_cli_dual
|
| 52 |
+
export INSTA360_SDK_LIB=$SDK/lib
|
| 53 |
+
tools/insta360_cli_dual discover # prints the serials of connected cameras as JSON
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Set the camera USB mode to Android (phone control) mode and install the udev rule shipped with the SDK so
|
| 57 |
+
the device is accessible without root.
|
flexiv-umi-infer/tools/insta360_cli_dual.cc
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Non-interactive CLI helper around Insta360 CameraSDK.
|
| 2 |
+
// Output is JSON on stdout, errors are JSON-with-error or plain on stderr.
|
| 3 |
+
//
|
| 4 |
+
// Usage:
|
| 5 |
+
// insta360_cli discover
|
| 6 |
+
// insta360_cli info
|
| 7 |
+
// insta360_cli battery
|
| 8 |
+
// insta360_cli storage
|
| 9 |
+
// insta360_cli record <seconds> [resolution_enum] [bitrate_bps]
|
| 10 |
+
// insta360_cli photo
|
| 11 |
+
// insta360_cli files
|
| 12 |
+
// insta360_cli stream <seconds> // dumps h264 to ./01_*.h264 / ./02_*.h264
|
| 13 |
+
// // and per-frame metadata to ./meta_*.jsonl
|
| 14 |
+
// insta360_cli download <remote> <local>
|
| 15 |
+
#include <camera/camera.h>
|
| 16 |
+
#include <camera/device_discovery.h>
|
| 17 |
+
#include <camera/photography_settings.h>
|
| 18 |
+
|
| 19 |
+
#include <chrono>
|
| 20 |
+
#include <cstdint>
|
| 21 |
+
#include <cstdio>
|
| 22 |
+
#include <cstdlib>
|
| 23 |
+
#include <cstring>
|
| 24 |
+
#include <fstream>
|
| 25 |
+
#include <iomanip>
|
| 26 |
+
#include <iostream>
|
| 27 |
+
#include <memory>
|
| 28 |
+
#include <mutex>
|
| 29 |
+
#include <sstream>
|
| 30 |
+
#include <string>
|
| 31 |
+
#include <thread>
|
| 32 |
+
#include <vector>
|
| 33 |
+
|
| 34 |
+
namespace ic = ins_camera;
|
| 35 |
+
|
| 36 |
+
// Optional serial filter set by --serial=<SN> on the command line.
|
| 37 |
+
static std::string g_serial;
|
| 38 |
+
// Set by --service-port=<N>. When two processes each drive one camera they need different
|
| 39 |
+
// ports, otherwise the second SDK service collides and GetAvailableDevices() reports serial_not_found.
|
| 40 |
+
static int g_service_port = 0;
|
| 41 |
+
|
| 42 |
+
static std::string ts_string() {
|
| 43 |
+
auto now = std::chrono::system_clock::now();
|
| 44 |
+
std::time_t t = std::chrono::system_clock::to_time_t(now);
|
| 45 |
+
std::tm tm{};
|
| 46 |
+
localtime_r(&t, &tm);
|
| 47 |
+
std::stringstream ss;
|
| 48 |
+
ss << std::put_time(&tm, "%Y%m%d_%H%M%S");
|
| 49 |
+
return ss.str();
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
static const char* camera_type_str(ic::CameraType t) {
|
| 53 |
+
switch (t) {
|
| 54 |
+
case ic::CameraType::Insta360OneX: return "Insta360OneX";
|
| 55 |
+
case ic::CameraType::Insta360OneR: return "Insta360OneR";
|
| 56 |
+
case ic::CameraType::Insta360OneRS: return "Insta360OneRS";
|
| 57 |
+
case ic::CameraType::Insta360OneX2: return "Insta360OneX2";
|
| 58 |
+
case ic::CameraType::Insta360X3: return "Insta360X3";
|
| 59 |
+
case ic::CameraType::Insta360X4: return "Insta360X4";
|
| 60 |
+
case ic::CameraType::Insta360X5: return "Insta360X5";
|
| 61 |
+
case ic::CameraType::Insta360X4Air: return "Insta360X4Air";
|
| 62 |
+
default: return "Unknown";
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
static const char* card_state_str(int s) {
|
| 67 |
+
switch (s) {
|
| 68 |
+
case ic::STOR_CS_PASS: return "OK";
|
| 69 |
+
case ic::STOR_CS_NOCARD: return "NO_CARD";
|
| 70 |
+
case ic::STOR_CS_NOSPACE: return "NO_SPACE";
|
| 71 |
+
case ic::STOR_CS_INVALID_FORMAT: return "INVALID_FORMAT";
|
| 72 |
+
case ic::STOR_CS_WPCARD: return "WRITE_PROTECTED";
|
| 73 |
+
default: return "ERROR";
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
static int cmd_discover() {
|
| 78 |
+
ic::DeviceDiscovery disc;
|
| 79 |
+
auto list = disc.GetAvailableDevices();
|
| 80 |
+
std::cout << "{\"devices\":[";
|
| 81 |
+
for (size_t i = 0; i < list.size(); ++i) {
|
| 82 |
+
const auto& d = list[i];
|
| 83 |
+
std::cout << (i ? "," : "")
|
| 84 |
+
<< "{\"serial\":\"" << d.serial_number << "\","
|
| 85 |
+
<< "\"name\":\"" << d.camera_name << "\","
|
| 86 |
+
<< "\"type\":\"" << camera_type_str(d.camera_type) << "\","
|
| 87 |
+
<< "\"fw\":\"" << d.fw_version << "\"}";
|
| 88 |
+
}
|
| 89 |
+
std::cout << "]}" << std::endl;
|
| 90 |
+
disc.FreeDeviceDescriptors(list);
|
| 91 |
+
return 0;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// Open a device. With --serial=<SN>, opens that specific camera; otherwise list[0].
|
| 95 |
+
static std::shared_ptr<ic::Camera> open_first(ic::CameraType* type_out = nullptr) {
|
| 96 |
+
ic::DeviceDiscovery disc;
|
| 97 |
+
auto list = disc.GetAvailableDevices();
|
| 98 |
+
if (list.empty()) {
|
| 99 |
+
std::cerr << "{\"error\":\"no_device\"}" << std::endl;
|
| 100 |
+
return nullptr;
|
| 101 |
+
}
|
| 102 |
+
size_t pick = 0;
|
| 103 |
+
if (!g_serial.empty()) {
|
| 104 |
+
bool found = false;
|
| 105 |
+
for (size_t i = 0; i < list.size(); ++i) {
|
| 106 |
+
if (list[i].serial_number == g_serial) { pick = i; found = true; break; }
|
| 107 |
+
}
|
| 108 |
+
if (!found) {
|
| 109 |
+
std::cerr << "{\"error\":\"serial_not_found\",\"serial\":\"" << g_serial << "\"}" << std::endl;
|
| 110 |
+
disc.FreeDeviceDescriptors(list);
|
| 111 |
+
return nullptr;
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
auto cam = std::make_shared<ic::Camera>(list[pick].info);
|
| 115 |
+
// The SDK header requires SetServicePort to be called before Open().
|
| 116 |
+
if (g_service_port > 0) cam->SetServicePort(g_service_port);
|
| 117 |
+
if (!cam->Open()) {
|
| 118 |
+
std::cerr << "{\"error\":\"open_failed\"}" << std::endl;
|
| 119 |
+
disc.FreeDeviceDescriptors(list);
|
| 120 |
+
return nullptr;
|
| 121 |
+
}
|
| 122 |
+
if (type_out) *type_out = list[pick].camera_type;
|
| 123 |
+
disc.FreeDeviceDescriptors(list);
|
| 124 |
+
return cam;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
static int cmd_info() {
|
| 128 |
+
ic::CameraType type;
|
| 129 |
+
auto cam = open_first(&type);
|
| 130 |
+
if (!cam) return 1;
|
| 131 |
+
auto preview = cam->GetPreviewParam();
|
| 132 |
+
auto enc = cam->GetVideoEncodeType();
|
| 133 |
+
std::cout << "{\"type\":\"" << camera_type_str(type) << "\","
|
| 134 |
+
<< "\"name\":\"" << preview.camera_name << "\","
|
| 135 |
+
<< "\"encode\":\"" << (enc == ic::VideoEncodeType::H265 ? "H265" : "H264") << "\","
|
| 136 |
+
<< "\"sweep_time\":" << preview.sweep_time << ","
|
| 137 |
+
<< "\"delay_timestamp\":" << preview.delay_timestamp
|
| 138 |
+
<< "}" << std::endl;
|
| 139 |
+
cam->Close();
|
| 140 |
+
return 0;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
static int cmd_battery() {
|
| 144 |
+
auto cam = open_first();
|
| 145 |
+
if (!cam) return 1;
|
| 146 |
+
ic::BatteryStatus bs{};
|
| 147 |
+
bool ok = cam->GetBatteryStatus(bs);
|
| 148 |
+
if (ok) {
|
| 149 |
+
std::cout << "{\"power_type\":\"" << (bs.power_type == ic::ADAPTER ? "ADAPTER" : "BATTERY") << "\","
|
| 150 |
+
<< "\"level\":" << bs.battery_level << ","
|
| 151 |
+
<< "\"scale\":" << bs.battery_scale << "}" << std::endl;
|
| 152 |
+
} else {
|
| 153 |
+
std::cerr << "{\"error\":\"get_battery_failed\"}" << std::endl;
|
| 154 |
+
}
|
| 155 |
+
cam->Close();
|
| 156 |
+
return ok ? 0 : 1;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
static int cmd_storage() {
|
| 160 |
+
auto cam = open_first();
|
| 161 |
+
if (!cam) return 1;
|
| 162 |
+
ic::StorageStatus st{};
|
| 163 |
+
bool ok = cam->GetStorageState(st);
|
| 164 |
+
if (ok) {
|
| 165 |
+
std::cout << "{\"state\":\"" << card_state_str(st.state) << "\","
|
| 166 |
+
<< "\"free\":" << st.free_space << ","
|
| 167 |
+
<< "\"total\":" << st.total_space << "}" << std::endl;
|
| 168 |
+
} else {
|
| 169 |
+
std::cerr << "{\"error\":\"get_storage_failed\"}" << std::endl;
|
| 170 |
+
}
|
| 171 |
+
cam->Close();
|
| 172 |
+
return ok ? 0 : 1;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
static int cmd_offset() {
|
| 176 |
+
auto cam = open_first();
|
| 177 |
+
if (!cam) return 1;
|
| 178 |
+
auto offsets = cam->GetCameraOffset();
|
| 179 |
+
auto preview = cam->GetPreviewParam();
|
| 180 |
+
std::cout << "{\"offset_count\":" << offsets.size();
|
| 181 |
+
for (size_t i = 0; i < offsets.size(); ++i) {
|
| 182 |
+
std::cout << ",\"offset_" << i << "\":\"" << offsets[i] << "\"";
|
| 183 |
+
}
|
| 184 |
+
// also dump preview_param.offset (may differ)
|
| 185 |
+
std::cout << ",\"preview_offset_count\":" << preview.offset.size();
|
| 186 |
+
for (size_t i = 0; i < preview.offset.size(); ++i) {
|
| 187 |
+
std::cout << ",\"preview_offset_" << i << "\":\"" << preview.offset[i] << "\"";
|
| 188 |
+
}
|
| 189 |
+
std::cout << ",\"lens_type\":" << static_cast<int>(cam->GetCameraLensType());
|
| 190 |
+
std::cout << "}" << std::endl;
|
| 191 |
+
cam->Close();
|
| 192 |
+
return 0;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
static int cmd_files() {
|
| 196 |
+
auto cam = open_first();
|
| 197 |
+
if (!cam) return 1;
|
| 198 |
+
auto files = cam->GetCameraFilesList();
|
| 199 |
+
std::cout << "{\"files\":[";
|
| 200 |
+
for (size_t i = 0; i < files.size(); ++i) {
|
| 201 |
+
std::cout << (i ? "," : "") << "\"" << files[i] << "\"";
|
| 202 |
+
}
|
| 203 |
+
std::cout << "]}" << std::endl;
|
| 204 |
+
cam->Close();
|
| 205 |
+
return 0;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
static int cmd_record(int argc, char** argv) {
|
| 209 |
+
int seconds = 5;
|
| 210 |
+
int res_enum = static_cast<int>(ic::VideoResolution::RES_3840_1920P30);
|
| 211 |
+
int bitrate = 1024 * 1024 * 40;
|
| 212 |
+
if (argc >= 3) seconds = std::atoi(argv[2]);
|
| 213 |
+
if (argc >= 4) res_enum = std::atoi(argv[3]);
|
| 214 |
+
if (argc >= 5) bitrate = std::atoi(argv[4]);
|
| 215 |
+
|
| 216 |
+
ic::CameraType type;
|
| 217 |
+
auto cam = open_first(&type);
|
| 218 |
+
if (!cam) return 1;
|
| 219 |
+
|
| 220 |
+
if (!cam->SetVideoSubMode(ic::SubVideoMode::VIDEO_NORMAL)) {
|
| 221 |
+
std::cerr << "{\"error\":\"set_submode_failed\"}" << std::endl;
|
| 222 |
+
cam->Close(); return 2;
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
ic::RecordParams rp{};
|
| 226 |
+
rp.resolution = static_cast<ic::VideoResolution>(res_enum);
|
| 227 |
+
rp.bitrate = bitrate;
|
| 228 |
+
if (!cam->SetVideoCaptureParams(rp, ic::CameraFunctionMode::FUNCTION_MODE_NORMAL_VIDEO)) {
|
| 229 |
+
std::cerr << "{\"error\":\"set_capture_params_failed\"}" << std::endl;
|
| 230 |
+
cam->Close(); return 3;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
if (!cam->StartRecording()) {
|
| 234 |
+
std::cerr << "{\"error\":\"start_record_failed\"}" << std::endl;
|
| 235 |
+
cam->Close(); return 4;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
std::cerr << "{\"event\":\"recording\",\"seconds\":" << seconds << "}" << std::endl;
|
| 239 |
+
std::this_thread::sleep_for(std::chrono::seconds(seconds));
|
| 240 |
+
|
| 241 |
+
auto url = cam->StopRecording();
|
| 242 |
+
if (url.Empty()) {
|
| 243 |
+
std::cerr << "{\"error\":\"stop_record_failed\"}" << std::endl;
|
| 244 |
+
cam->Close(); return 5;
|
| 245 |
+
}
|
| 246 |
+
std::cout << "{\"urls\":[";
|
| 247 |
+
const auto& origins = url.OriginUrls();
|
| 248 |
+
for (size_t i = 0; i < origins.size(); ++i) {
|
| 249 |
+
std::cout << (i ? "," : "") << "\"" << origins[i] << "\"";
|
| 250 |
+
}
|
| 251 |
+
std::cout << "]}" << std::endl;
|
| 252 |
+
cam->Close();
|
| 253 |
+
return 0;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
static int cmd_photo() {
|
| 257 |
+
auto cam = open_first();
|
| 258 |
+
if (!cam) return 1;
|
| 259 |
+
auto url = cam->TakePhoto();
|
| 260 |
+
if (url.Empty()) {
|
| 261 |
+
std::cerr << "{\"error\":\"take_photo_failed\"}" << std::endl;
|
| 262 |
+
cam->Close(); return 2;
|
| 263 |
+
}
|
| 264 |
+
std::cout << "{\"urls\":[";
|
| 265 |
+
const auto& o = url.OriginUrls();
|
| 266 |
+
for (size_t i = 0; i < o.size(); ++i) std::cout << (i ? "," : "") << "\"" << o[i] << "\"";
|
| 267 |
+
std::cout << "]}" << std::endl;
|
| 268 |
+
cam->Close();
|
| 269 |
+
return 0;
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
// Stream delegate. Writes H.264 streams to disk (per-lens) and emits NDJSON
|
| 273 |
+
// metadata. The metadata target is configurable: file (--out) or stdout
|
| 274 |
+
// (live-mode for Python consumers).
|
| 275 |
+
//
|
| 276 |
+
// Timestamps from the SDK callbacks are in MILLISECONDS (camera uptime since
|
| 277 |
+
// boot, same domain across video/audio/gyro/exposure).
|
| 278 |
+
class DumpDelegate : public ic::StreamDelegate {
|
| 279 |
+
public:
|
| 280 |
+
enum class MetaSink { File, Stdout };
|
| 281 |
+
|
| 282 |
+
DumpDelegate(const std::string& tag, MetaSink sink) : sink_(sink) {
|
| 283 |
+
std::string base = "./" + tag;
|
| 284 |
+
// Output paths can be overridden by env; point them at a fifo to feed ffmpeg live.
|
| 285 |
+
// Unset keeps the original behavior (<timestamp>_0x.h264 in cwd).
|
| 286 |
+
const char* p1 = getenv("INSTA360_VIDEO0_PATH");
|
| 287 |
+
const char* p2 = getenv("INSTA360_VIDEO1_PATH");
|
| 288 |
+
fp1_ = fopen(p1 && *p1 ? p1 : (base + "_01.h264").c_str(), "wb");
|
| 289 |
+
fp2_ = fopen(p2 && *p2 ? p2 : (base + "_02.h264").c_str(), "wb");
|
| 290 |
+
// With a fifo the default 4KB buffer stalls downstream ffmpeg, so flush per packet.
|
| 291 |
+
fifo_ = (p1 && *p1) || (p2 && *p2);
|
| 292 |
+
if (sink_ == MetaSink::File) meta_.open(base + "_meta.jsonl");
|
| 293 |
+
}
|
| 294 |
+
~DumpDelegate() {
|
| 295 |
+
if (fp1_) fclose(fp1_);
|
| 296 |
+
if (fp2_) fclose(fp2_);
|
| 297 |
+
if (meta_.is_open()) meta_.close();
|
| 298 |
+
}
|
| 299 |
+
void OnAudioData(const uint8_t*, size_t size, int64_t ts) override {
|
| 300 |
+
std::ostringstream s;
|
| 301 |
+
s << "{\"kind\":\"audio\",\"ts\":" << ts << ",\"size\":" << size << "}";
|
| 302 |
+
emit(s.str());
|
| 303 |
+
}
|
| 304 |
+
void OnVideoData(const uint8_t* data, size_t size, int64_t ts, uint8_t streamType, int idx) override {
|
| 305 |
+
if (idx == 0 && fp1_) { fwrite(data, 1, size, fp1_); if (fifo_) fflush(fp1_); }
|
| 306 |
+
if (idx == 1 && fp2_) { fwrite(data, 1, size, fp2_); if (fifo_) fflush(fp2_); }
|
| 307 |
+
std::ostringstream s;
|
| 308 |
+
s << "{\"kind\":\"video\",\"idx\":" << idx
|
| 309 |
+
<< ",\"ts\":" << ts << ",\"size\":" << size
|
| 310 |
+
<< ",\"stream_type\":" << static_cast<int>(streamType) << "}";
|
| 311 |
+
emit(s.str());
|
| 312 |
+
}
|
| 313 |
+
void OnGyroData(const std::vector<ic::GyroData>& d) override {
|
| 314 |
+
for (const auto& smp : d) {
|
| 315 |
+
std::ostringstream s;
|
| 316 |
+
s << "{\"kind\":\"gyro\",\"ts\":" << smp.timestamp
|
| 317 |
+
<< ",\"ax\":" << smp.ax << ",\"ay\":" << smp.ay << ",\"az\":" << smp.az
|
| 318 |
+
<< ",\"gx\":" << smp.gx << ",\"gy\":" << smp.gy << ",\"gz\":" << smp.gz
|
| 319 |
+
<< "}";
|
| 320 |
+
emit(s.str());
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
void OnExposureData(const ic::ExposureData& e) override {
|
| 324 |
+
std::ostringstream s;
|
| 325 |
+
s << "{\"kind\":\"exposure\",\"ts\":" << e.timestamp
|
| 326 |
+
<< ",\"exposure_time\":" << e.exposure_time << "}";
|
| 327 |
+
emit(s.str());
|
| 328 |
+
}
|
| 329 |
+
private:
|
| 330 |
+
void emit(const std::string& line) {
|
| 331 |
+
std::lock_guard<std::mutex> g(mu_);
|
| 332 |
+
if (sink_ == MetaSink::Stdout) {
|
| 333 |
+
std::cout << line << "\n";
|
| 334 |
+
std::cout.flush(); // line-buffered for live consumers
|
| 335 |
+
} else if (meta_.is_open()) {
|
| 336 |
+
meta_ << line << "\n";
|
| 337 |
+
}
|
| 338 |
+
}
|
| 339 |
+
MetaSink sink_;
|
| 340 |
+
FILE* fp1_ = nullptr;
|
| 341 |
+
FILE* fp2_ = nullptr;
|
| 342 |
+
bool fifo_ = false;
|
| 343 |
+
std::ofstream meta_;
|
| 344 |
+
std::mutex mu_;
|
| 345 |
+
};
|
| 346 |
+
|
| 347 |
+
static int cmd_stream(int argc, char** argv) {
|
| 348 |
+
// Args: insta360_cli stream <seconds> [resolution_enum=2] [using_lrv=1]
|
| 349 |
+
// [bitrate_kbps=512] [enable_audio=0] [enable_gyro=1]
|
| 350 |
+
// [meta_to_stdout=0]
|
| 351 |
+
// Default uses RES_1920_960P30 + LRV proxy. On X4 Air this avoids the USB
|
| 352 |
+
// mass-storage mode switch we observed at higher panoramic resolutions.
|
| 353 |
+
// When meta_to_stdout=1, NDJSON lines are emitted to stdout in real time
|
| 354 |
+
// (Python consumers can readline() as packets arrive); the final summary
|
| 355 |
+
// line is still printed last.
|
| 356 |
+
int seconds = 5;
|
| 357 |
+
int res_enum = static_cast<int>(ic::VideoResolution::RES_1920_960P30);
|
| 358 |
+
int using_lrv = 1;
|
| 359 |
+
int bitrate_kbps = 512;
|
| 360 |
+
int enable_audio = 0;
|
| 361 |
+
int enable_gyro = 1;
|
| 362 |
+
int meta_to_stdout = 0;
|
| 363 |
+
if (argc >= 3) seconds = std::atoi(argv[2]);
|
| 364 |
+
if (argc >= 4) res_enum = std::atoi(argv[3]);
|
| 365 |
+
if (argc >= 5) using_lrv = std::atoi(argv[4]);
|
| 366 |
+
if (argc >= 6) bitrate_kbps = std::atoi(argv[5]);
|
| 367 |
+
if (argc >= 7) enable_audio = std::atoi(argv[6]);
|
| 368 |
+
if (argc >= 8) enable_gyro = std::atoi(argv[7]);
|
| 369 |
+
if (argc >= 9) meta_to_stdout = std::atoi(argv[8]);
|
| 370 |
+
|
| 371 |
+
ic::CameraType type;
|
| 372 |
+
auto cam = open_first(&type);
|
| 373 |
+
if (!cam) return 1;
|
| 374 |
+
|
| 375 |
+
auto resolution = static_cast<ic::VideoResolution>(res_enum);
|
| 376 |
+
if (type >= ic::CameraType::Insta360X4) {
|
| 377 |
+
if (!cam->SetVideoSubMode(ic::SubVideoMode::VIDEO_LIVEVIEW)) {
|
| 378 |
+
std::cerr << "{\"error\":\"set_liveview_submode_failed\"}" << std::endl;
|
| 379 |
+
cam->Close(); return 2;
|
| 380 |
+
}
|
| 381 |
+
ic::RecordParams rp{};
|
| 382 |
+
rp.resolution = resolution;
|
| 383 |
+
rp.bitrate = 0;
|
| 384 |
+
if (!cam->SetVideoCaptureParams(rp, ic::CameraFunctionMode::FUNCTION_MODE_LIVE_STREAM)) {
|
| 385 |
+
std::cerr << "{\"error\":\"set_liveview_params_failed\"}" << std::endl;
|
| 386 |
+
cam->Close(); return 3;
|
| 387 |
+
}
|
| 388 |
+
// Give the camera a brief settle window after mode switching.
|
| 389 |
+
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
auto tag = ts_string();
|
| 393 |
+
auto sink = meta_to_stdout ? DumpDelegate::MetaSink::Stdout
|
| 394 |
+
: DumpDelegate::MetaSink::File;
|
| 395 |
+
auto delegate = std::shared_ptr<ic::StreamDelegate>(new DumpDelegate(tag, sink));
|
| 396 |
+
cam->SetStreamDelegate(delegate);
|
| 397 |
+
|
| 398 |
+
ic::LiveStreamParam param{};
|
| 399 |
+
param.video_resolution = resolution;
|
| 400 |
+
param.lrv_video_resulution = ic::VideoResolution::RES_1440_720P30;
|
| 401 |
+
param.video_bitrate = static_cast<uint32_t>(bitrate_kbps) * 1024;
|
| 402 |
+
param.lrv_video_bitrate = 512 * 1024;
|
| 403 |
+
param.enable_audio = enable_audio != 0;
|
| 404 |
+
param.using_lrv = using_lrv != 0;
|
| 405 |
+
param.enable_gyro = enable_gyro != 0;
|
| 406 |
+
|
| 407 |
+
std::cerr << "{\"event\":\"starting\",\"resolution\":" << res_enum
|
| 408 |
+
<< ",\"using_lrv\":" << param.using_lrv
|
| 409 |
+
<< ",\"bitrate_kbps\":" << bitrate_kbps
|
| 410 |
+
<< ",\"audio\":" << param.enable_audio
|
| 411 |
+
<< ",\"gyro\":" << param.enable_gyro << "}" << std::endl;
|
| 412 |
+
|
| 413 |
+
if (!cam->StartLiveStreaming(param)) {
|
| 414 |
+
std::cerr << "{\"error\":\"start_live_failed\"}" << std::endl;
|
| 415 |
+
cam->Close(); return 4;
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
std::cerr << "{\"event\":\"streaming\",\"seconds\":" << seconds << ",\"tag\":\"" << tag << "\"}" << std::endl;
|
| 419 |
+
std::this_thread::sleep_for(std::chrono::seconds(seconds));
|
| 420 |
+
|
| 421 |
+
cam->StopLiveStreaming();
|
| 422 |
+
// Settle so writes flush.
|
| 423 |
+
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
| 424 |
+
// Final summary line, always last on stdout, regardless of sink.
|
| 425 |
+
std::cout << "{\"kind\":\"summary\",\"tag\":\"" << tag << "\","
|
| 426 |
+
<< "\"files\":[\"" << tag << "_01.h264\",\"" << tag << "_02.h264\","
|
| 427 |
+
<< "\"" << tag << "_meta.jsonl\"]}" << std::endl;
|
| 428 |
+
cam->Close();
|
| 429 |
+
return 0;
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
static int cmd_download(int argc, char** argv) {
|
| 433 |
+
if (argc < 4) { std::cerr << "usage: insta360_cli download <remote> <local>\n"; return 64; }
|
| 434 |
+
std::string remote = argv[2], local = argv[3];
|
| 435 |
+
auto cam = open_first();
|
| 436 |
+
if (!cam) return 1;
|
| 437 |
+
int64_t last_pct = -1;
|
| 438 |
+
bool ok = cam->DownloadCameraFile(remote, local, [&](int64_t cur, int64_t tot){
|
| 439 |
+
if (tot <= 0) return;
|
| 440 |
+
int64_t pct = cur * 100 / tot;
|
| 441 |
+
if (pct != last_pct) { std::cerr << "\rdownload " << pct << "%" << std::flush; last_pct = pct; }
|
| 442 |
+
});
|
| 443 |
+
std::cerr << std::endl;
|
| 444 |
+
cam->Close();
|
| 445 |
+
if (!ok) { std::cerr << "{\"error\":\"download_failed\"}" << std::endl; return 2; }
|
| 446 |
+
std::cout << "{\"local\":\"" << local << "\"}" << std::endl;
|
| 447 |
+
return 0;
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
int main(int argc, char** argv) {
|
| 451 |
+
ic::SetLogLevel(ic::LogLevel::ERR);
|
| 452 |
+
// Strip --serial=<SN> from anywhere in argv.
|
| 453 |
+
int out = 1;
|
| 454 |
+
for (int i = 1; i < argc; ++i) {
|
| 455 |
+
std::string a = argv[i];
|
| 456 |
+
if (a.rfind("--serial=", 0) == 0) { g_serial = a.substr(9); continue; }
|
| 457 |
+
if (a.rfind("--service-port=", 0) == 0) {
|
| 458 |
+
g_service_port = std::atoi(a.substr(15).c_str());
|
| 459 |
+
continue;
|
| 460 |
+
}
|
| 461 |
+
argv[out++] = argv[i];
|
| 462 |
+
}
|
| 463 |
+
argc = out;
|
| 464 |
+
if (argc < 2) {
|
| 465 |
+
std::cerr << "usage: insta360_cli_dual [--serial=<SN>] [--service-port=<N>] <discover|info|battery|storage|files|offset|photo|record|stream|download> ...\n"
|
| 466 |
+
<< " env INSTA360_VIDEO0_PATH / INSTA360_VIDEO1_PATH: write idx0/idx1 h264 to the given path (may be a fifo)" << std::endl;
|
| 467 |
+
return 64;
|
| 468 |
+
}
|
| 469 |
+
std::string cmd = argv[1];
|
| 470 |
+
if (cmd == "discover") return cmd_discover();
|
| 471 |
+
if (cmd == "info") return cmd_info();
|
| 472 |
+
if (cmd == "battery") return cmd_battery();
|
| 473 |
+
if (cmd == "storage") return cmd_storage();
|
| 474 |
+
if (cmd == "files") return cmd_files();
|
| 475 |
+
if (cmd == "offset") return cmd_offset();
|
| 476 |
+
if (cmd == "photo") return cmd_photo();
|
| 477 |
+
if (cmd == "record") return cmd_record(argc, argv);
|
| 478 |
+
if (cmd == "stream") return cmd_stream(argc, argv);
|
| 479 |
+
if (cmd == "download") return cmd_download(argc, argv);
|
| 480 |
+
std::cerr << "unknown command: " << cmd << std::endl;
|
| 481 |
+
return 64;
|
| 482 |
+
}
|
flexiv-umi-infer/umi_infer/__init__.py
ADDED
|
File without changes
|
flexiv-umi-infer/umi_infer/check_cam.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""Camera self-check: grab one frame per wrist camera and verify it matches the training setup.
|
| 4 |
+
|
| 5 |
+
A wrong camera fails silently: the policy raises no error, it just moves wrongly (e.g. the
|
| 6 |
+
rear lens was picked). This checks:
|
| 7 |
+
(1) body <-> arm: CAM_SERIAL (env INSTA360_LEFT_SN / INSTA360_RIGHT_SN) vs the camera_serial
|
| 8 |
+
in the hand-eye records (FLEXIV_HANDEYE_RUNS/{left,right}/poses.json).
|
| 9 |
+
(2) half: CAM_HALF (env INSTA360_LEFT_HALF / INSTA360_RIGHT_HALF) vs the img_half the
|
| 10 |
+
extrinsic E was solved on.
|
| 11 |
+
(3) size: CAM_OUT_SIZE vs observation.images.*_ego shape in the dataset meta/info.json.
|
| 12 |
+
|
| 13 |
+
It also saves live frames next to the training first frame: very different framing means the
|
| 14 |
+
images are out of distribution, where the policy tends to freeze or drift.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
python -m umi_infer.check_cam [--dataset <lerobot root>] # grab + save + compare
|
| 18 |
+
python -m umi_infer.check_cam --no-compare # grab only
|
| 19 |
+
python -m umi_infer.check_cam --out-dir /tmp/camchk
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import glob
|
| 26 |
+
import json
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
import time
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from .robot_io.cam_ids import CAM_HALF, CAM_OUT_SIZE, CAM_SERIAL, HANDEYE_RUNS, SIDES
|
| 34 |
+
|
| 35 |
+
DATA = "" # training LeRobot dataset root, set from --dataset
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def check_identity():
|
| 39 |
+
"""Compare the configured camera mapping with the hand-eye records; a mismatch means one side changed."""
|
| 40 |
+
print("=== (1) camera body <-> arm ===")
|
| 41 |
+
if not HANDEYE_RUNS:
|
| 42 |
+
print(" FLEXIV_HANDEYE_RUNS not set, skipping")
|
| 43 |
+
return True
|
| 44 |
+
ok = True
|
| 45 |
+
for s in SIDES:
|
| 46 |
+
p = os.path.join(HANDEYE_RUNS, s, "poses.json")
|
| 47 |
+
if not os.path.exists(p):
|
| 48 |
+
print(" %-6s calibration record missing (%s), cannot verify" % (s, p))
|
| 49 |
+
ok = False
|
| 50 |
+
continue
|
| 51 |
+
d = json.load(open(p))
|
| 52 |
+
want = d["meta"].get("camera_serial")
|
| 53 |
+
got = CAM_SERIAL[s]
|
| 54 |
+
halves = {x.get("img_half") for x in d["items"]}
|
| 55 |
+
mark = "OK" if want == got else "FAIL"
|
| 56 |
+
print(" %s %-6s calibrated body %s | configured %s" % (mark, s, want, got))
|
| 57 |
+
if want != got:
|
| 58 |
+
ok = False
|
| 59 |
+
print(" -> E and images come from different cameras! Fix INSTA360_LEFT_SN / INSTA360_RIGHT_SN")
|
| 60 |
+
hm = "OK" if halves == {CAM_HALF[s]} else "FAIL"
|
| 61 |
+
print(" %s %-6s calibrated half %s | configured %r"
|
| 62 |
+
% (hm, s, halves, CAM_HALF[s]))
|
| 63 |
+
if halves != {CAM_HALF[s]}:
|
| 64 |
+
ok = False
|
| 65 |
+
return ok
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def check_dataset_shape():
|
| 69 |
+
print("\n=== (3) image size vs training ===")
|
| 70 |
+
if not DATA:
|
| 71 |
+
print(" no --dataset given, skipping")
|
| 72 |
+
return True
|
| 73 |
+
info = json.load(open(os.path.join(DATA, "meta", "info.json")))
|
| 74 |
+
for k in ("observation.images.left_ego", "observation.images.right_ego"):
|
| 75 |
+
shp = info["features"][k]["shape"]
|
| 76 |
+
mark = "OK" if shp[0] == CAM_OUT_SIZE == shp[1] else "FAIL"
|
| 77 |
+
print(" %s %-34s training %s | live %dx%d" % (mark, k, shp, CAM_OUT_SIZE, CAM_OUT_SIZE))
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def training_first_frame(side, out_path):
|
| 82 |
+
"""Decode a reference frame from the training set (first frame of the first episode)."""
|
| 83 |
+
import cv2
|
| 84 |
+
key = "left_ego" if side == "left" else "right_ego"
|
| 85 |
+
pats = [os.path.join(DATA, "videos", "**", "observation.images.%s" % key, "*.mp4"),
|
| 86 |
+
os.path.join(DATA, "videos", "**", "*%s*.mp4" % key)]
|
| 87 |
+
vids = []
|
| 88 |
+
for pat in pats:
|
| 89 |
+
vids = sorted(glob.glob(pat, recursive=True))
|
| 90 |
+
if vids:
|
| 91 |
+
break
|
| 92 |
+
if not DATA or not vids:
|
| 93 |
+
print(" %-6s no training video found (under %s/videos), skipping compare" % (side, DATA))
|
| 94 |
+
return None
|
| 95 |
+
# Decode with ffmpeg in software, not cv2.VideoCapture: training videos are AV1 and some
|
| 96 |
+
# cv2 builds try hardware decoding, fail, and return empty frames.
|
| 97 |
+
import subprocess
|
| 98 |
+
from .robot_io.insta_live import FFMPEG
|
| 99 |
+
r = subprocess.run([FFMPEG, "-v", "error", "-i", vids[0], "-frames:v", "1",
|
| 100 |
+
"-y", out_path], capture_output=True, text=True)
|
| 101 |
+
bgr = cv2.imread(out_path) if os.path.exists(out_path) else None
|
| 102 |
+
if bgr is None:
|
| 103 |
+
print(" %-6s cannot decode training video: %s (%s)"
|
| 104 |
+
% (side, vids[0], (r.stderr or "").strip()[:120]))
|
| 105 |
+
return None
|
| 106 |
+
print(" %-6s training first frame %s -> %s" % (side, os.path.basename(vids[0]), out_path))
|
| 107 |
+
return bgr
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def main():
|
| 111 |
+
ap = argparse.ArgumentParser(description="Wrist camera self-check")
|
| 112 |
+
ap.add_argument("--out-dir", default="/tmp/umi_camchk")
|
| 113 |
+
ap.add_argument("--dataset", default="", help="training LeRobot dataset root (size check + first-frame compare)")
|
| 114 |
+
ap.add_argument("--no-compare", action="store_true", help="skip comparison with the training first frame")
|
| 115 |
+
ap.add_argument("--warmup", type=float, default=8.0, help="seconds to wait for the first frame")
|
| 116 |
+
a = ap.parse_args()
|
| 117 |
+
global DATA
|
| 118 |
+
DATA = a.dataset
|
| 119 |
+
if not all(CAM_SERIAL.values()):
|
| 120 |
+
print("set INSTA360_LEFT_SN / INSTA360_RIGHT_SN first")
|
| 121 |
+
return 1
|
| 122 |
+
os.makedirs(a.out_dir, exist_ok=True)
|
| 123 |
+
|
| 124 |
+
id_ok = check_identity()
|
| 125 |
+
check_dataset_shape()
|
| 126 |
+
|
| 127 |
+
print("\n=== (2) live frame grab ===")
|
| 128 |
+
import cv2
|
| 129 |
+
from .robot_io.insta_live import InstaDualCamera
|
| 130 |
+
dual = InstaDualCamera(serials={s: CAM_SERIAL[s] for s in SIDES},
|
| 131 |
+
halves={s: CAM_HALF[s] for s in SIDES},
|
| 132 |
+
out_size=CAM_OUT_SIZE)
|
| 133 |
+
dual.start()
|
| 134 |
+
try:
|
| 135 |
+
if not dual.wait_ready(max(a.warmup, 20.0)):
|
| 136 |
+
print("FAIL: cameras not ready. Check: USB mode set to Android control / udev rules / "
|
| 137 |
+
"a leftover insta360_cli holding the device")
|
| 138 |
+
return 1
|
| 139 |
+
time.sleep(1.5)
|
| 140 |
+
got = {}
|
| 141 |
+
for s in SIDES:
|
| 142 |
+
rgb, stamp = dual.get_frame(s)
|
| 143 |
+
if rgb is None:
|
| 144 |
+
print(" FAIL %-6s no frame" % s)
|
| 145 |
+
continue
|
| 146 |
+
p = os.path.join(a.out_dir, "live_%s.png" % s)
|
| 147 |
+
cv2.imwrite(p, cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR))
|
| 148 |
+
got[s] = rgb
|
| 149 |
+
print(" OK %-6s %s %dx%d mean %.1f -> %s"
|
| 150 |
+
% (s, CAM_SERIAL[s], rgb.shape[1], rgb.shape[0], float(rgb.mean()), p))
|
| 151 |
+
print(" fps %.1f" % dual.fps(s))
|
| 152 |
+
if not a.no_compare and got:
|
| 153 |
+
print("\n=== side by side with training first frame (very different framing = out of distribution) ===")
|
| 154 |
+
for s in SIDES:
|
| 155 |
+
if s not in got:
|
| 156 |
+
continue
|
| 157 |
+
ref = training_first_frame(s, os.path.join(a.out_dir, "train_%s.png" % s))
|
| 158 |
+
if ref is None:
|
| 159 |
+
continue
|
| 160 |
+
live = cv2.cvtColor(got[s], cv2.COLOR_RGB2BGR)
|
| 161 |
+
if ref.shape[:2] != live.shape[:2]:
|
| 162 |
+
ref = cv2.resize(ref, (live.shape[1], live.shape[0]))
|
| 163 |
+
pair = np.hstack([ref, live])
|
| 164 |
+
cv2.putText(pair, "TRAIN", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
|
| 165 |
+
(0, 255, 0), 3)
|
| 166 |
+
cv2.putText(pair, "LIVE", (live.shape[1] + 20, 50),
|
| 167 |
+
cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 3)
|
| 168 |
+
p = os.path.join(a.out_dir, "cmp_%s.png" % s)
|
| 169 |
+
cv2.imwrite(p, pair)
|
| 170 |
+
print(" %-6s left=training right=live -> %s" % (s, p))
|
| 171 |
+
finally:
|
| 172 |
+
dual.stop()
|
| 173 |
+
|
| 174 |
+
print("\nbody/half check: %s" % ("PASS" if id_ok else "FAIL, fix before continuing"))
|
| 175 |
+
print("images saved to %s" % a.out_dir)
|
| 176 |
+
return 0 if id_ok else 1
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
sys.exit(main())
|
flexiv-umi-infer/umi_infer/codec/__init__.py
ADDED
|
File without changes
|
flexiv-umi-infer/umi_infer/codec/umi_decode.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pure-numpy pose / rotation decode helpers for the UMI pi05 policy.
|
| 3 |
+
|
| 4 |
+
Mirrors the openpi-umi training transforms so model output can be decoded
|
| 5 |
+
without importing ``openpi`` (useful on a robot and in unit tests).
|
| 6 |
+
|
| 7 |
+
Per hand, the pi05 UMI model emits a relative action chunk of shape (H, A):
|
| 8 |
+
|
| 9 |
+
rel_xyz(3) | rotation(rot_dim) | gripper(1) A = 3 + rot_dim + 1
|
| 10 |
+
|
| 11 |
+
where ``rot_dim`` is 6 for ``rot6d`` (default), 4 for ``quat_xyzw`` and 3 for
|
| 12 |
+
``axis_angle``. Each action is the next EEF pose expressed *relative to the
|
| 13 |
+
current EEF frame*, so the world target is ``world = current @ rel``.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"rot_dim",
|
| 22 |
+
"rot6d_to_matrix",
|
| 23 |
+
"quat_xyzw_to_matrix",
|
| 24 |
+
"axis_angle_to_matrix",
|
| 25 |
+
"pose_xyzw_to_matrix",
|
| 26 |
+
"matrix_to_quat_xyzw",
|
| 27 |
+
"invert_transform",
|
| 28 |
+
"decode_actions_to_world",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _unit(v: np.ndarray, eps: float = 1e-8) -> np.ndarray:
|
| 33 |
+
return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), eps)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def rot_dim(rotation_repr: str) -> int:
|
| 37 |
+
"""Number of rotation channels for a given representation."""
|
| 38 |
+
return {"rot6d": 6, "quat_xyzw": 4, "axis_angle": 3}[rotation_repr]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def rot6d_to_matrix(rot6d: np.ndarray) -> np.ndarray:
|
| 42 |
+
"""6-D continuous rotation (first two basis columns + Gram-Schmidt) -> (..., 3, 3)."""
|
| 43 |
+
rot6d = np.asarray(rot6d, dtype=np.float32)
|
| 44 |
+
a1 = rot6d[..., :3]
|
| 45 |
+
a2 = rot6d[..., 3:6]
|
| 46 |
+
b1 = _unit(a1)
|
| 47 |
+
b2 = _unit(a2 - np.sum(b1 * a2, axis=-1, keepdims=True) * b1)
|
| 48 |
+
b3 = np.cross(b1, b2)
|
| 49 |
+
return np.stack([b1, b2, b3], axis=-1).astype(np.float32)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def quat_xyzw_to_matrix(quat: np.ndarray) -> np.ndarray:
|
| 53 |
+
"""Quaternion [qx, qy, qz, qw] -> rotation matrix (..., 3, 3)."""
|
| 54 |
+
x, y, z, w = np.moveaxis(_unit(np.asarray(quat, dtype=np.float32)), -1, 0)
|
| 55 |
+
xx, yy, zz = x * x, y * y, z * z
|
| 56 |
+
xy, xz, yz = x * y, x * z, y * z
|
| 57 |
+
wx, wy, wz = w * x, w * y, w * z
|
| 58 |
+
m = np.empty((*np.asarray(quat).shape[:-1], 3, 3), dtype=np.float32)
|
| 59 |
+
m[..., 0, 0] = 1.0 - 2.0 * (yy + zz)
|
| 60 |
+
m[..., 0, 1] = 2.0 * (xy - wz)
|
| 61 |
+
m[..., 0, 2] = 2.0 * (xz + wy)
|
| 62 |
+
m[..., 1, 0] = 2.0 * (xy + wz)
|
| 63 |
+
m[..., 1, 1] = 1.0 - 2.0 * (xx + zz)
|
| 64 |
+
m[..., 1, 2] = 2.0 * (yz - wx)
|
| 65 |
+
m[..., 2, 0] = 2.0 * (xz - wy)
|
| 66 |
+
m[..., 2, 1] = 2.0 * (yz + wx)
|
| 67 |
+
m[..., 2, 2] = 1.0 - 2.0 * (xx + yy)
|
| 68 |
+
return m
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def axis_angle_to_matrix(axis_angle: np.ndarray) -> np.ndarray:
|
| 72 |
+
"""Axis-angle (3-vector, magnitude=angle) -> rotation matrix (..., 3, 3)."""
|
| 73 |
+
axis_angle = np.asarray(axis_angle, dtype=np.float32)
|
| 74 |
+
angle = np.linalg.norm(axis_angle, axis=-1, keepdims=True)
|
| 75 |
+
axis = axis_angle / np.maximum(angle, 1e-8)
|
| 76 |
+
x, y, z = np.moveaxis(axis, -1, 0)
|
| 77 |
+
ca = np.cos(angle[..., 0])
|
| 78 |
+
sa = np.sin(angle[..., 0])
|
| 79 |
+
omc = 1.0 - ca
|
| 80 |
+
m = np.empty((*axis_angle.shape[:-1], 3, 3), dtype=np.float32)
|
| 81 |
+
m[..., 0, 0] = ca + x * x * omc
|
| 82 |
+
m[..., 0, 1] = x * y * omc - z * sa
|
| 83 |
+
m[..., 0, 2] = x * z * omc + y * sa
|
| 84 |
+
m[..., 1, 0] = y * x * omc + z * sa
|
| 85 |
+
m[..., 1, 1] = ca + y * y * omc
|
| 86 |
+
m[..., 1, 2] = y * z * omc - x * sa
|
| 87 |
+
m[..., 2, 0] = z * x * omc - y * sa
|
| 88 |
+
m[..., 2, 1] = z * y * omc + x * sa
|
| 89 |
+
m[..., 2, 2] = ca + z * z * omc
|
| 90 |
+
small = angle[..., 0] < 1e-8
|
| 91 |
+
if np.any(small):
|
| 92 |
+
m[small] = np.eye(3, dtype=np.float32)
|
| 93 |
+
return m
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def pose_xyzw_to_matrix(pose: np.ndarray) -> np.ndarray:
|
| 97 |
+
"""7-D pose [x, y, z, qx, qy, qz, qw] -> homogeneous transform (..., 4, 4)."""
|
| 98 |
+
pose = np.asarray(pose, dtype=np.float32)
|
| 99 |
+
m = np.broadcast_to(np.eye(4, dtype=np.float32), (*pose.shape[:-1], 4, 4)).copy()
|
| 100 |
+
m[..., :3, 3] = pose[..., :3]
|
| 101 |
+
m[..., :3, :3] = quat_xyzw_to_matrix(pose[..., 3:7])
|
| 102 |
+
return m
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def matrix_to_quat_xyzw(matrix: np.ndarray) -> np.ndarray:
|
| 106 |
+
"""Rotation matrix -> [qx, qy, qz, qw], canonicalised to qw >= 0."""
|
| 107 |
+
matrix = np.asarray(matrix, dtype=np.float32)
|
| 108 |
+
q = np.empty((*matrix.shape[:-2], 4), dtype=np.float32)
|
| 109 |
+
trace = np.trace(matrix, axis1=-2, axis2=-1)
|
| 110 |
+
for idx in np.ndindex(trace.shape):
|
| 111 |
+
m = matrix[idx]
|
| 112 |
+
tr = trace[idx]
|
| 113 |
+
if tr > 0:
|
| 114 |
+
s = np.sqrt(tr + 1.0) * 2.0
|
| 115 |
+
q[idx] = [(m[2, 1] - m[1, 2]) / s, (m[0, 2] - m[2, 0]) / s, (m[1, 0] - m[0, 1]) / s, 0.25 * s]
|
| 116 |
+
else:
|
| 117 |
+
axis = int(np.argmax(np.diag(m)))
|
| 118 |
+
if axis == 0:
|
| 119 |
+
s = np.sqrt(1.0 + m[0, 0] - m[1, 1] - m[2, 2]) * 2.0
|
| 120 |
+
q[idx] = [0.25 * s, (m[0, 1] + m[1, 0]) / s, (m[0, 2] + m[2, 0]) / s, (m[2, 1] - m[1, 2]) / s]
|
| 121 |
+
elif axis == 1:
|
| 122 |
+
s = np.sqrt(1.0 + m[1, 1] - m[0, 0] - m[2, 2]) * 2.0
|
| 123 |
+
q[idx] = [(m[0, 1] + m[1, 0]) / s, 0.25 * s, (m[1, 2] + m[2, 1]) / s, (m[0, 2] - m[2, 0]) / s]
|
| 124 |
+
else:
|
| 125 |
+
s = np.sqrt(1.0 + m[2, 2] - m[0, 0] - m[1, 1]) * 2.0
|
| 126 |
+
q[idx] = [(m[0, 2] + m[2, 0]) / s, (m[1, 2] + m[2, 1]) / s, 0.25 * s, (m[1, 0] - m[0, 1]) / s]
|
| 127 |
+
q = _unit(q)
|
| 128 |
+
q = np.where(q[..., 3:4] < 0, -q, q) # qw >= 0
|
| 129 |
+
return q.astype(np.float32)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _rel_rotation_to_matrix(rot: np.ndarray, rotation_repr: str) -> np.ndarray:
|
| 133 |
+
if rotation_repr == "rot6d":
|
| 134 |
+
return rot6d_to_matrix(rot)
|
| 135 |
+
if rotation_repr == "quat_xyzw":
|
| 136 |
+
return quat_xyzw_to_matrix(rot)
|
| 137 |
+
if rotation_repr == "axis_angle":
|
| 138 |
+
return axis_angle_to_matrix(rot)
|
| 139 |
+
raise ValueError(f"Unsupported rotation_repr: {rotation_repr}")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def invert_transform(t: np.ndarray) -> np.ndarray:
|
| 143 |
+
"""Inverse of a homogeneous SE(3) transform (..., 4, 4)."""
|
| 144 |
+
t = np.asarray(t, dtype=np.float32)
|
| 145 |
+
inv = np.broadcast_to(np.eye(4, dtype=np.float32), t.shape).copy()
|
| 146 |
+
r_t = np.swapaxes(t[..., :3, :3], -1, -2)
|
| 147 |
+
inv[..., :3, :3] = r_t
|
| 148 |
+
inv[..., :3, 3] = -np.einsum("...ij,...j->...i", r_t, t[..., :3, 3])
|
| 149 |
+
return inv
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def decode_actions_to_world(
|
| 153 |
+
current_pose_xyzw: np.ndarray,
|
| 154 |
+
actions: np.ndarray,
|
| 155 |
+
rotation_repr: str = "rot6d",
|
| 156 |
+
eef_extrinsic: np.ndarray | None = None,
|
| 157 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 158 |
+
"""Decode a relative action chunk to absolute world EEF targets.
|
| 159 |
+
|
| 160 |
+
Each action is the next pose expressed in the CURRENT gripper frame, so
|
| 161 |
+
``world = current @ rel`` and the output lands in the SAME frame as
|
| 162 |
+
``current_pose_xyzw``. Feed the robot's live base-frame gripper pose as
|
| 163 |
+
``current`` and the targets come out in the base frame (the world-frame
|
| 164 |
+
UMI->base alignment ``M`` cancels).
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
current_pose_xyzw: current absolute EEF pose, 7-vec [x,y,z,qx,qy,qz,qw].
|
| 168 |
+
actions: (H, A) relative action chunk: rel_xyz(3) | rot(rot_dim) | gripper(1).
|
| 169 |
+
rotation_repr: "rot6d" (default), "quat_xyzw" or "axis_angle".
|
| 170 |
+
eef_extrinsic: optional (4,4) SE(3) ``E`` mapping the UMI gripper frame to
|
| 171 |
+
the robot's reported gripper frame (``current_robot = current_umi @ E``).
|
| 172 |
+
When given, each relative step is re-expressed in the robot frame by
|
| 173 |
+
conjugation ``rel' = E^-1 @ rel @ E`` before composing. Covers both a
|
| 174 |
+
gripper-orientation calibration AND a flange->TCP translation offset
|
| 175 |
+
(e.g. a flange->TCP offset ``[0,0,0.118]`` if FK reports the flange).
|
| 176 |
+
``None`` (default) == identity == plain ``world = current @ rel``.
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
world_pos: (H, 3) absolute positions.
|
| 180 |
+
world_quat: (H, 4) absolute orientations [qx,qy,qz,qw], qw >= 0.
|
| 181 |
+
gripper: (H,) absolute gripper command (model output, unscaled).
|
| 182 |
+
"""
|
| 183 |
+
current = pose_xyzw_to_matrix(np.asarray(current_pose_xyzw, np.float32)) # (4,4)
|
| 184 |
+
actions = np.asarray(actions, dtype=np.float32)
|
| 185 |
+
rd = rot_dim(rotation_repr)
|
| 186 |
+
n = actions.shape[0]
|
| 187 |
+
rel = np.broadcast_to(np.eye(4, dtype=np.float32), (n, 4, 4)).copy()
|
| 188 |
+
rel[:, :3, 3] = actions[:, 0:3]
|
| 189 |
+
rel[:, :3, :3] = _rel_rotation_to_matrix(actions[:, 3:3 + rd], rotation_repr)
|
| 190 |
+
if eef_extrinsic is not None:
|
| 191 |
+
e = np.asarray(eef_extrinsic, dtype=np.float32).reshape(4, 4)
|
| 192 |
+
e_inv = invert_transform(e)
|
| 193 |
+
rel = np.einsum("ij,njk,kl->nil", e_inv, rel, e) # rel' = E^-1 @ rel @ E
|
| 194 |
+
world = np.einsum("ij,njk->nik", current, rel)
|
| 195 |
+
return (
|
| 196 |
+
world[:, :3, 3].astype(np.float32),
|
| 197 |
+
matrix_to_quat_xyzw(world[:, :3, :3]),
|
| 198 |
+
actions[:, 3 + rd].astype(np.float32),
|
| 199 |
+
)
|
flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# ruff: noqa: E402
|
| 3 |
+
"""Server-side inference core for the pi05 UMI policy (single- or dual-hand).
|
| 4 |
+
|
| 5 |
+
Inference only: transport (websocket / ROS / ...) lives elsewhere and calls in
|
| 6 |
+
here. The policy is loaded once; each call returns ABSOLUTE target EEF poses and
|
| 7 |
+
gripper commands.
|
| 8 |
+
|
| 9 |
+
from umi_infer.codec.umi_pi05_server import init_server, infer_target_eef
|
| 10 |
+
|
| 11 |
+
init_server(checkpoint_dir="<ckpt>/<step>", config="pi05_umi_v3") # once
|
| 12 |
+
result = infer_target_eef(observation) # per request
|
| 13 |
+
|
| 14 |
+
(or hold ``UmiPi05Server(checkpoint_dir=...)`` and call ``.infer(observation)``).
|
| 15 |
+
|
| 16 |
+
openpi comes from the installed package, or from ``openpi_root`` / ``--openpi-root``
|
| 17 |
+
pointing at a tree containing ``src/openpi``.
|
| 18 |
+
|
| 19 |
+
The leading ``2`` below is the TIME window [previous, current] of the same hands;
|
| 20 |
+
``nh`` = config ``num_hands`` (1 or 2). Every pose is the gripper's 6-DOF pose.
|
| 21 |
+
|
| 22 |
+
observation (input):
|
| 23 |
+
"eef_pose": (2, nh, 7) x,y,z, qx,qy,qz,qw (always xyzw; (2, 7) ok for nh=1)
|
| 24 |
+
"gripper": (2, nh) gripper width
|
| 25 |
+
"images": {config_image_key: (H, W, 3) uint8 RGB} for every configured view,
|
| 26 |
+
or "image": one (H, W, 3) array for single-view configs
|
| 27 |
+
"prompt": str (optional), "upsample": int (optional)
|
| 28 |
+
|
| 29 |
+
result (output; the leading nh axis is dropped when nh == 1):
|
| 30 |
+
"target_eef_pose": (nh, M, 7) spline-upsampled target poses (xyzw)
|
| 31 |
+
"target_gripper": (nh, M) absolute gripper command
|
| 32 |
+
"times": (M,) sample times in model-step units [0, H-1]
|
| 33 |
+
"target_eef_pose_raw", "target_gripper_raw": raw decoded chunk (H samples)
|
| 34 |
+
"rel_actions": (H, nh*10) raw relative chunk per hand: rel_xyz | rot6d | grip
|
| 35 |
+
"num_samples", "upsample", "num_hands", "horizon", "rotation_repr"
|
| 36 |
+
|
| 37 |
+
Decode: each step is relative to the CURRENT gripper, so ``world = current @ rel``
|
| 38 |
+
and the targets come out in the same frame as the input ``eef_pose``. The chunk is
|
| 39 |
+
then upsampled to M = (H-1)*N+1 samples (cubic xyz, SO(3) RotationSpline, PCHIP
|
| 40 |
+
gripper; N=1 disables). See umi_spline.py.
|
| 41 |
+
|
| 42 |
+
Coordinate frames: feed the robot's live base-frame gripper pose (from FK). UMI
|
| 43 |
+
training data uses a different world frame, but since actions are body-relative
|
| 44 |
+
and composed onto the real current pose, that world alignment cancels and must
|
| 45 |
+
NOT be applied here. The only remaining correction is the optional extrinsic E
|
| 46 |
+
(UMI gripper frame -> robot gripper frame): ``target = current @ (E^-1 @ rel @ E)``,
|
| 47 |
+
e.g. ``--tcp-offset`` when FK reports the flange instead of the TCP.
|
| 48 |
+
Default E = identity.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
from __future__ import annotations
|
| 52 |
+
|
| 53 |
+
import argparse
|
| 54 |
+
import os
|
| 55 |
+
from pathlib import Path
|
| 56 |
+
import sys
|
| 57 |
+
import tempfile
|
| 58 |
+
import time
|
| 59 |
+
|
| 60 |
+
import numpy as np
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
from . import umi_decode, umi_spline
|
| 64 |
+
except ImportError: # run as a plain script
|
| 65 |
+
import umi_decode
|
| 66 |
+
import umi_spline
|
| 67 |
+
|
| 68 |
+
# Optional openpi source tree (<root>/src/openpi). Empty = use the installed openpi package
|
| 69 |
+
# (e.g. `pip install -e openpi-umi`).
|
| 70 |
+
DEFAULT_OPENPI_ROOT = os.environ.get("OPENPI_ROOT", "")
|
| 71 |
+
DEFAULT_CONFIG = "pi05_umi_v3"
|
| 72 |
+
DEFAULT_PROMPT = "fold the clothes"
|
| 73 |
+
# Cubic-spline upsample factor applied to the decoded chunk before it is returned to the
|
| 74 |
+
# client: each of the H model steps is split into N sub-steps -> (H-1)*N+1 samples.
|
| 75 |
+
# 1 disables interpolation (raw chunk passes through). Override per request via obs["upsample"].
|
| 76 |
+
DEFAULT_UPSAMPLE = 4
|
| 77 |
+
|
| 78 |
+
# Keep symlinked temp cwd (for the tokenizer) alive for the process lifetime.
|
| 79 |
+
_TEMP_MODEL_CWDS: list[tempfile.TemporaryDirectory] = []
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ----------------------------------------------------------------------------- openpi setup
|
| 83 |
+
def add_openpi_to_path(openpi_root) -> None:
|
| 84 |
+
"""Put ``<openpi_root>/src`` first on sys.path; no-op when openpi_root is empty."""
|
| 85 |
+
if not openpi_root:
|
| 86 |
+
return
|
| 87 |
+
src = (Path(openpi_root) / "src").resolve()
|
| 88 |
+
if not (src / "openpi").is_dir():
|
| 89 |
+
raise FileNotFoundError(f"openpi package not found under {src}")
|
| 90 |
+
if str(src) not in sys.path:
|
| 91 |
+
sys.path.insert(0, str(src))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def prepare_model_assets(model_dir: Path | None) -> None:
|
| 95 |
+
"""Make OpenPI's fixed relative tokenizer path reachable (resolve real paths BEFORE calling)."""
|
| 96 |
+
if model_dir is None:
|
| 97 |
+
return
|
| 98 |
+
if Path("model/paligemma-3b-pt-224/tokenizer.model").exists():
|
| 99 |
+
return
|
| 100 |
+
source = Path(model_dir) / "paligemma-3b-pt-224" / "tokenizer.model"
|
| 101 |
+
if not source.exists():
|
| 102 |
+
print(f"[warn] tokenizer not found at {source}; continuing with current cwd", flush=True)
|
| 103 |
+
return
|
| 104 |
+
temp_cwd = tempfile.TemporaryDirectory(prefix="umi_server_")
|
| 105 |
+
_TEMP_MODEL_CWDS.append(temp_cwd)
|
| 106 |
+
root = Path(temp_cwd.name)
|
| 107 |
+
(root / "model").symlink_to(Path(model_dir).resolve(), target_is_directory=True)
|
| 108 |
+
os.chdir(root)
|
| 109 |
+
print(f"[info] tokenizer cwd: {root / 'model'} -> {model_dir}", flush=True)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def resolve_norm_stats(checkpoint_dir: Path, explicit: Path | None) -> Path:
|
| 113 |
+
if explicit is not None:
|
| 114 |
+
return Path(explicit).resolve()
|
| 115 |
+
cand = sorted((Path(checkpoint_dir) / "assets").glob("*/norm_stats.json"))
|
| 116 |
+
if not cand:
|
| 117 |
+
raise FileNotFoundError(f"No norm_stats.json under {checkpoint_dir}/assets; pass norm_stats=")
|
| 118 |
+
return cand[0].resolve()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def resolve_eef_extrinsic(spec) -> np.ndarray | None:
|
| 122 |
+
"""Build the optional (4,4) gripper-frame extrinsic E (UMI gripper -> robot gripper).
|
| 123 |
+
|
| 124 |
+
Accepts: None (identity, no correction); a (4,4) array / nested list; a path to a
|
| 125 |
+
.npy holding a (4,4); or a single float z = a pure translation [0,0,z] (e.g. a
|
| 126 |
+
flange->TCP offset when FK reports the flange, not the gripper).
|
| 127 |
+
"""
|
| 128 |
+
if spec is None:
|
| 129 |
+
return None
|
| 130 |
+
if isinstance(spec, (int, float)):
|
| 131 |
+
e = np.eye(4, dtype=np.float32)
|
| 132 |
+
e[2, 3] = float(spec)
|
| 133 |
+
return e
|
| 134 |
+
if isinstance(spec, (str, Path)):
|
| 135 |
+
e = np.load(Path(spec))
|
| 136 |
+
else:
|
| 137 |
+
e = np.asarray(spec, dtype=np.float32)
|
| 138 |
+
e = np.asarray(e, dtype=np.float32).reshape(4, 4)
|
| 139 |
+
return e
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ----------------------------------------------------------------------------- server core
|
| 143 |
+
class UmiPi05Server:
|
| 144 |
+
"""Loads the trained policy once and turns observations into world EEF targets."""
|
| 145 |
+
|
| 146 |
+
def __init__(
|
| 147 |
+
self,
|
| 148 |
+
checkpoint_dir: str | Path,
|
| 149 |
+
config: str = DEFAULT_CONFIG,
|
| 150 |
+
openpi_root: str | Path = DEFAULT_OPENPI_ROOT,
|
| 151 |
+
norm_stats: str | Path | None = None,
|
| 152 |
+
device: str = "cuda:0",
|
| 153 |
+
num_denoise_steps: int = 10,
|
| 154 |
+
prompt: str = DEFAULT_PROMPT,
|
| 155 |
+
model_dir: str | Path | None = None,
|
| 156 |
+
rotation_repr: str | None = None,
|
| 157 |
+
image_key: str | None = None,
|
| 158 |
+
enable_torch_compile: bool = False,
|
| 159 |
+
gripper_min: float | None = None,
|
| 160 |
+
gripper_max: float | None = None,
|
| 161 |
+
eef_extrinsic=None,
|
| 162 |
+
upsample: int = DEFAULT_UPSAMPLE,
|
| 163 |
+
):
|
| 164 |
+
add_openpi_to_path(openpi_root)
|
| 165 |
+
|
| 166 |
+
# Resolve real paths BEFORE prepare_model_assets may chdir into a temp dir.
|
| 167 |
+
checkpoint_dir = Path(checkpoint_dir).resolve()
|
| 168 |
+
norm_stats_path = resolve_norm_stats(checkpoint_dir, norm_stats)
|
| 169 |
+
if model_dir is None:
|
| 170 |
+
# Directory holding paligemma-3b-pt-224/tokenizer.model (offline machines).
|
| 171 |
+
model_dir = os.environ.get("TOKENIZER_DIR") or (Path(openpi_root) / "model" if openpi_root else None)
|
| 172 |
+
prepare_model_assets(model_dir if model_dir and Path(model_dir).exists() else None)
|
| 173 |
+
|
| 174 |
+
from openpi.policies import policy_config as _policy_config
|
| 175 |
+
from openpi.training import config as _config
|
| 176 |
+
|
| 177 |
+
train_config = _config.get_config(config)
|
| 178 |
+
|
| 179 |
+
# ---- state switch: toggle state input via env without a new config ----
|
| 180 |
+
# UMI_SEND_STATE=1 -> send state (state_dropout_prob=0.0)
|
| 181 |
+
# UMI_SEND_STATE=0 -> no state (state_dropout_prob=1.0, image-only)
|
| 182 |
+
# STATE_DROPOUT_PROB=<float> -> explicit value (takes precedence)
|
| 183 |
+
# Avoid 0<prob<1 at inference: StateDropout samples per call, so output
|
| 184 |
+
# becomes non-deterministic. Use 0 or 1 even for models trained with 0.5.
|
| 185 |
+
# Fields missing from the config are skipped and reported, not raised.
|
| 186 |
+
import os as _os_sw, dataclasses as _dc_sw
|
| 187 |
+
_ov_sw = {}
|
| 188 |
+
_v_sw = _os_sw.environ.get("UMI_SEND_STATE")
|
| 189 |
+
if _v_sw not in (None, ""):
|
| 190 |
+
_send = _v_sw.strip().lower() not in ("0", "false", "no", "off")
|
| 191 |
+
_ov_sw["state_dropout_prob"] = 0.0 if _send else 1.0
|
| 192 |
+
_v_sw = _os_sw.environ.get("STATE_DROPOUT_PROB")
|
| 193 |
+
if _v_sw not in (None, ""):
|
| 194 |
+
_ov_sw["state_dropout_prob"] = float(_v_sw) # explicit value wins
|
| 195 |
+
_v_sw = _os_sw.environ.get("INCLUDE_INTER_GRIPPER")
|
| 196 |
+
if _v_sw not in (None, ""):
|
| 197 |
+
_ov_sw["include_inter_gripper_state"] = _v_sw.strip().lower() not in ("0", "false", "no", "off")
|
| 198 |
+
_skip_sw = {k: v for k, v in _ov_sw.items() if not hasattr(train_config.data, k)}
|
| 199 |
+
_ov_sw = {k: v for k, v in _ov_sw.items() if hasattr(train_config.data, k)}
|
| 200 |
+
if _ov_sw:
|
| 201 |
+
train_config = _dc_sw.replace(train_config, data=_dc_sw.replace(train_config.data, **_ov_sw))
|
| 202 |
+
print(f"[state-switch] data override: {_ov_sw}", flush=True)
|
| 203 |
+
if _skip_sw:
|
| 204 |
+
print(f"[state-switch] SKIPPED (fields not in this config): {_skip_sw}", flush=True)
|
| 205 |
+
print(f"[state-switch] effective state_dropout_prob="
|
| 206 |
+
f"{getattr(train_config.data, 'state_dropout_prob', 'N/A')} "
|
| 207 |
+
f"(0=state sent, 1=no state)", flush=True)
|
| 208 |
+
# ---- state switch end ----
|
| 209 |
+
data = train_config.data # LeRobotUmiDataConfig
|
| 210 |
+
|
| 211 |
+
self.rotation_repr = rotation_repr or getattr(data, "rotation_repr", "rot6d")
|
| 212 |
+
# Quaternion order: openpi's UmiInputs reads pose[3:7] per config.pose_format,
|
| 213 |
+
# while umi_decode always expects xyzw. This module's interface is always xyzw;
|
| 214 |
+
# poses are reordered once (to wxyz if needed) only before entering openpi.
|
| 215 |
+
self.pose_format = getattr(data, "pose_format", "xyz_quat_xyzw")
|
| 216 |
+
if self.pose_format not in ("xyz_quat_xyzw", "xyz_quat_wxyz"):
|
| 217 |
+
raise ValueError(
|
| 218 |
+
"pose_format=%r is not supported (only the two quaternion layouts); "
|
| 219 |
+
"other formats need matching handling in umi_decode" % self.pose_format)
|
| 220 |
+
self.image_key = image_key or (
|
| 221 |
+
data.right_wrist_image_key or data.left_wrist_image_key or data.base_image_key
|
| 222 |
+
)
|
| 223 |
+
if self.image_key is None:
|
| 224 |
+
raise ValueError("Could not determine image key from config; pass image_key=")
|
| 225 |
+
# All configured camera views, in a stable order (dual-hand configs have two).
|
| 226 |
+
self.image_keys = [k for k in (data.base_image_key, data.left_wrist_image_key,
|
| 227 |
+
data.right_wrist_image_key) if k]
|
| 228 |
+
self.num_hands = getattr(data, "num_hands", 1)
|
| 229 |
+
self.horizon = train_config.model.action_horizon
|
| 230 |
+
self.prompt = prompt
|
| 231 |
+
self.gripper_min = gripper_min
|
| 232 |
+
self.gripper_max = gripper_max
|
| 233 |
+
self.eef_extrinsic = resolve_eef_extrinsic(eef_extrinsic)
|
| 234 |
+
self.upsample = max(int(upsample), 1)
|
| 235 |
+
|
| 236 |
+
print(f"[info] config={config} rotation_repr={self.rotation_repr} image_key={self.image_key}", flush=True)
|
| 237 |
+
print(f"[info] pose_format={self.pose_format} (interface is always xyzw; "
|
| 238 |
+
f"before openpi: {'reorder to wxyz' if self.pose_format == 'xyz_quat_wxyz' else 'no reorder'})",
|
| 239 |
+
flush=True)
|
| 240 |
+
print(f"[info] checkpoint={checkpoint_dir}", flush=True)
|
| 241 |
+
print(f"[info] norm_stats={norm_stats_path}", flush=True)
|
| 242 |
+
if self.upsample > 1:
|
| 243 |
+
n_out = umi_spline.num_samples_for(self.horizon, self.upsample)
|
| 244 |
+
print(f"[info] spline upsample x{self.upsample}: {self.horizon} -> {n_out} samples/chunk "
|
| 245 |
+
f"(cubic xyz, SO(3) RotationSpline, PCHIP gripper)", flush=True)
|
| 246 |
+
else:
|
| 247 |
+
print("[info] spline upsample disabled (upsample=1; raw chunk returned)", flush=True)
|
| 248 |
+
if self.eef_extrinsic is not None:
|
| 249 |
+
print(f"[info] eef_extrinsic (UMI gripper -> robot gripper) =\n{self.eef_extrinsic.round(4)}", flush=True)
|
| 250 |
+
else:
|
| 251 |
+
print("[info] eef_extrinsic=identity (target = current @ rel; base frame in == base frame out)", flush=True)
|
| 252 |
+
|
| 253 |
+
if not enable_torch_compile:
|
| 254 |
+
import torch
|
| 255 |
+
torch.compile = lambda fn, *a, **k: fn # type: ignore[assignment]
|
| 256 |
+
|
| 257 |
+
self.policy = _policy_config.create_trained_policy(
|
| 258 |
+
train_config,
|
| 259 |
+
checkpoint_dir,
|
| 260 |
+
default_prompt=prompt,
|
| 261 |
+
norm_stats_path=norm_stats_path,
|
| 262 |
+
pytorch_device=device,
|
| 263 |
+
sample_kwargs={"num_steps": num_denoise_steps},
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
def _eef_for_model(self, eef_xyzw: np.ndarray) -> np.ndarray:
|
| 267 |
+
"""Reorder xyzw poses to config.pose_format (model input only).
|
| 268 |
+
|
| 269 |
+
openpi reads xyz_quat_xyzw as (x,y,z,w) and xyz_quat_wxyz via
|
| 270 |
+
pose[..., [4,5,6,3]], so wxyz configs get (w,x,y,z) here.
|
| 271 |
+
"""
|
| 272 |
+
if self.pose_format == "xyz_quat_xyzw":
|
| 273 |
+
return eef_xyzw
|
| 274 |
+
e = np.asarray(eef_xyzw, np.float32)
|
| 275 |
+
# (...,3:7) is (x,y,z,w) -> take [w,x,y,z]
|
| 276 |
+
return np.concatenate([e[..., :3], e[..., [6, 3, 4, 5]]], axis=-1).astype(np.float32)
|
| 277 |
+
|
| 278 |
+
def _clip_gripper(self, gripper: np.ndarray) -> np.ndarray:
|
| 279 |
+
if self.gripper_min is None and self.gripper_max is None:
|
| 280 |
+
return gripper
|
| 281 |
+
lo = -np.inf if self.gripper_min is None else self.gripper_min
|
| 282 |
+
hi = np.inf if self.gripper_max is None else self.gripper_max
|
| 283 |
+
return np.clip(gripper, lo, hi)
|
| 284 |
+
|
| 285 |
+
# ---- the per-request entry point ----
|
| 286 |
+
def infer(self, observation: dict) -> dict:
|
| 287 |
+
"""observation -> {target_eef_pose (M,7), target_gripper (M,), rel_actions (H,A), ...}.
|
| 288 |
+
|
| 289 |
+
The decoded H-step chunk is cubic-spline upsampled to M = (H-1)*N+1 samples
|
| 290 |
+
before return (N = obs["upsample"] or the server default); ``target_eef_pose`` /
|
| 291 |
+
``target_gripper`` are that smooth, denser trajectory (what the client tracks).
|
| 292 |
+
The raw model chunk stays available as ``*_raw``. Set upsample=1 to disable
|
| 293 |
+
(then M == H and the interpolated arrays equal the raw ones).
|
| 294 |
+
|
| 295 |
+
``observation["eef_pose"]`` is always **xyzw** (see pose_format in __init__).
|
| 296 |
+
"""
|
| 297 |
+
nh = self.num_hands
|
| 298 |
+
eef = np.asarray(observation["eef_pose"], dtype=np.float32).reshape(2, nh, 7)
|
| 299 |
+
grip = np.asarray(observation["gripper"], dtype=np.float32).reshape(2, nh)
|
| 300 |
+
prompt = observation.get("prompt", self.prompt)
|
| 301 |
+
|
| 302 |
+
obs = {
|
| 303 |
+
# Model input follows config.pose_format; umi_decode below still uses xyzw eef.
|
| 304 |
+
"observation.state.eef_pose": self._eef_for_model(eef),
|
| 305 |
+
"observation.state.gripper_width": grip,
|
| 306 |
+
"prompt": prompt,
|
| 307 |
+
}
|
| 308 |
+
# images: single-hand callers pass "image" (one array); dual-hand callers pass
|
| 309 |
+
# "images": {config_image_key: array} covering every configured view.
|
| 310 |
+
if "images" in observation:
|
| 311 |
+
for k in self.image_keys:
|
| 312 |
+
if k not in observation["images"]:
|
| 313 |
+
raise ValueError(f"observation['images'] missing configured view {k!r}")
|
| 314 |
+
obs[k] = np.asarray(observation["images"][k])
|
| 315 |
+
else:
|
| 316 |
+
obs[self.image_key] = np.asarray(observation["image"])
|
| 317 |
+
actions = np.asarray(self.policy.infer(obs)["actions"], dtype=np.float32) # (H, nh*10)
|
| 318 |
+
|
| 319 |
+
try:
|
| 320 |
+
upsample = max(int(observation.get("upsample", self.upsample)), 1)
|
| 321 |
+
except (TypeError, ValueError):
|
| 322 |
+
upsample = self.upsample
|
| 323 |
+
|
| 324 |
+
# per-hand eef_extrinsic: a single (4,4) applies to every hand; a list/tuple
|
| 325 |
+
# of length nh gives one per hand (entries may be None).
|
| 326 |
+
ee = self.eef_extrinsic
|
| 327 |
+
ee_per_hand = list(ee) if isinstance(ee, (list, tuple)) else [ee] * nh
|
| 328 |
+
|
| 329 |
+
raw_pose, raw_gripper, tgt_pose, tgt_grip, times = [], [], [], [], None
|
| 330 |
+
for h in range(nh):
|
| 331 |
+
acts_h = actions[:, 10 * h : 10 * h + 10]
|
| 332 |
+
pos, quat, gripper = umi_decode.decode_actions_to_world(
|
| 333 |
+
eef[1, h], acts_h, self.rotation_repr, eef_extrinsic=ee_per_hand[h]
|
| 334 |
+
)
|
| 335 |
+
gripper = self._clip_gripper(gripper)
|
| 336 |
+
raw_pose.append(np.concatenate([pos, quat], axis=-1).astype(np.float32))
|
| 337 |
+
raw_gripper.append(gripper.astype(np.float32))
|
| 338 |
+
pos_i, quat_i, grip_i, times = umi_spline.resample_pose_chunk(
|
| 339 |
+
pos, quat, gripper, upsample=upsample)
|
| 340 |
+
tgt_pose.append(np.concatenate([pos_i, quat_i], axis=-1).astype(np.float32))
|
| 341 |
+
tgt_grip.append(self._clip_gripper(grip_i).astype(np.float32))
|
| 342 |
+
|
| 343 |
+
if nh == 1: # single-hand callers keep the original (M,7)/(M,) shapes
|
| 344 |
+
tgt_pose, tgt_grip, raw_pose, raw_gripper = tgt_pose[0], tgt_grip[0], raw_pose[0], raw_gripper[0]
|
| 345 |
+
else: # dual: stacked (nh, M, 7) / (nh, M)
|
| 346 |
+
tgt_pose, tgt_grip = np.stack(tgt_pose), np.stack(tgt_grip)
|
| 347 |
+
raw_pose, raw_gripper = np.stack(raw_pose), np.stack(raw_gripper)
|
| 348 |
+
|
| 349 |
+
return {
|
| 350 |
+
"target_eef_pose": tgt_pose, # (M,7) or (nh,M,7) -> client tracks this
|
| 351 |
+
"target_gripper": tgt_grip, # (M,) or (nh,M)
|
| 352 |
+
"times": times.astype(np.float32), # (M,) sample times in model-step units [0, H-1]
|
| 353 |
+
"num_samples": int(times.shape[0]), # M
|
| 354 |
+
"upsample": upsample, # N actually applied this call
|
| 355 |
+
"num_hands": nh,
|
| 356 |
+
"target_eef_pose_raw": raw_pose, # raw decoded chunk (pre-interpolation)
|
| 357 |
+
"target_gripper_raw": raw_gripper,
|
| 358 |
+
"rel_actions": actions, # (H, nh*10) raw relative chunk
|
| 359 |
+
"horizon": int(actions.shape[0]), # H (model action horizon)
|
| 360 |
+
"rotation_repr": self.rotation_repr,
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
# ----------------------------------------------------------------------------- module-level API
|
| 365 |
+
_SERVER: UmiPi05Server | None = None
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def init_server(**kwargs) -> UmiPi05Server:
|
| 369 |
+
"""Load the policy once. Pass the same kwargs as UmiPi05Server(...)."""
|
| 370 |
+
global _SERVER
|
| 371 |
+
_SERVER = UmiPi05Server(**kwargs)
|
| 372 |
+
return _SERVER
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def infer_target_eef(observation: dict) -> dict:
|
| 376 |
+
"""Per-request inference. Requires init_server(...) to have been called once.
|
| 377 |
+
|
| 378 |
+
This is the function the transport layer is expected to call.
|
| 379 |
+
"""
|
| 380 |
+
if _SERVER is None:
|
| 381 |
+
raise RuntimeError("call init_server(...) once before infer_target_eef(...)")
|
| 382 |
+
return _SERVER.infer(observation)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
# ----------------------------------------------------------------------------- self-test
|
| 386 |
+
def run_selftest(server: UmiPi05Server) -> None:
|
| 387 |
+
print("[selftest] one inference on synthetic obs...", flush=True)
|
| 388 |
+
cur = np.array([0.4, 0.0, 0.3, 0.0, 0.0, 0.0, 1.0], dtype=np.float32)
|
| 389 |
+
prev = cur.copy()
|
| 390 |
+
prev[0] -= 0.01 # the previous frame was 1cm behind -> nonzero motion
|
| 391 |
+
obs = {
|
| 392 |
+
"image": np.zeros((480, 640, 3), dtype=np.uint8),
|
| 393 |
+
"eef_pose": np.stack([prev, cur], axis=0), # (2,7)
|
| 394 |
+
"gripper": np.array([0.05, 0.05], dtype=np.float32), # (2,)
|
| 395 |
+
"prompt": server.prompt,
|
| 396 |
+
}
|
| 397 |
+
t0 = time.time()
|
| 398 |
+
out = infer_target_eef(obs)
|
| 399 |
+
dt = (time.time() - t0) * 1000
|
| 400 |
+
print(f"[selftest] OK infer={dt:.0f}ms horizon={out['horizon']} repr={out['rotation_repr']}", flush=True)
|
| 401 |
+
print(f"[selftest] upsample x{out['upsample']}: raw{out['target_eef_pose_raw'].shape} -> "
|
| 402 |
+
f"interp{out['target_eef_pose'].shape} (num_samples={out['num_samples']})", flush=True)
|
| 403 |
+
print(f"[selftest] target_eef_pose{out['target_eef_pose'].shape} target_gripper{out['target_gripper'].shape}",
|
| 404 |
+
flush=True)
|
| 405 |
+
# Knot reproduction: the first/last interpolated samples must equal the raw chunk endpoints.
|
| 406 |
+
# Compare the quaternion block sign-agnostically (q and -q are the same rotation).
|
| 407 |
+
def _pose_close(a, b, atol=1e-4):
|
| 408 |
+
pos_ok = np.allclose(a[:3], b[:3], atol=atol)
|
| 409 |
+
q1, q2 = a[3:7], b[3:7]
|
| 410 |
+
quat_ok = np.allclose(q1, q2, atol=atol) or np.allclose(q1, -q2, atol=atol)
|
| 411 |
+
return pos_ok and quat_ok
|
| 412 |
+
assert _pose_close(out['target_eef_pose'][0], out['target_eef_pose_raw'][0])
|
| 413 |
+
assert _pose_close(out['target_eef_pose'][-1], out['target_eef_pose_raw'][-1])
|
| 414 |
+
qn = np.linalg.norm(out['target_eef_pose'][:, 3:7], axis=-1)
|
| 415 |
+
print(f"[selftest] quat |q| in [{qn.min():.5f}, {qn.max():.5f}] (should be ~1); "
|
| 416 |
+
f"endpoints match raw chunk OK", flush=True)
|
| 417 |
+
print(f"[selftest] first target pose={np.round(out['target_eef_pose'][0], 4)} "
|
| 418 |
+
f"grip={out['target_gripper'][0]:.4f}", flush=True)
|
| 419 |
+
print(f"[selftest] last target pose={np.round(out['target_eef_pose'][-1], 4)} "
|
| 420 |
+
f"grip={out['target_gripper'][-1]:.4f}", flush=True)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def main() -> None:
|
| 424 |
+
ap = argparse.ArgumentParser(description="UMI pi05 inference server core (self-test / wiring helper)")
|
| 425 |
+
ap.add_argument("--checkpoint-dir", type=Path, required=True)
|
| 426 |
+
ap.add_argument("--config", default=DEFAULT_CONFIG)
|
| 427 |
+
ap.add_argument("--openpi-root", type=Path, default=DEFAULT_OPENPI_ROOT)
|
| 428 |
+
ap.add_argument("--norm-stats", type=Path, default=None)
|
| 429 |
+
ap.add_argument("--device", default="cuda:0")
|
| 430 |
+
ap.add_argument("--num-denoise-steps", type=int, default=10)
|
| 431 |
+
ap.add_argument("--prompt", default=DEFAULT_PROMPT)
|
| 432 |
+
ap.add_argument("--model-dir", type=Path, default=None)
|
| 433 |
+
ap.add_argument("--rotation-repr", default=None, choices=[None, "rot6d", "quat_xyzw", "axis_angle"])
|
| 434 |
+
ap.add_argument("--image-key", default=None)
|
| 435 |
+
ap.add_argument("--gripper-min", type=float, default=None)
|
| 436 |
+
ap.add_argument("--gripper-max", type=float, default=None)
|
| 437 |
+
ap.add_argument("--eef-extrinsic", type=Path, default=None,
|
| 438 |
+
help="path to a (4,4) .npy SE(3) E (UMI gripper -> robot gripper); default identity")
|
| 439 |
+
ap.add_argument("--tcp-offset", type=float, default=None,
|
| 440 |
+
help="shorthand: pure-translation extrinsic [0,0,z] (e.g. 0.118 if FK reports the flange)")
|
| 441 |
+
ap.add_argument("--upsample", type=int, default=DEFAULT_UPSAMPLE,
|
| 442 |
+
help="cubic-spline upsample factor N: H -> (H-1)*N+1 samples (1 disables; default 4)")
|
| 443 |
+
ap.add_argument("--selftest", action="store_true", help="run one inference on synthetic input (no transport)")
|
| 444 |
+
args = ap.parse_args()
|
| 445 |
+
|
| 446 |
+
eef_extrinsic = args.eef_extrinsic if args.eef_extrinsic is not None else args.tcp_offset
|
| 447 |
+
|
| 448 |
+
server = init_server(
|
| 449 |
+
checkpoint_dir=args.checkpoint_dir,
|
| 450 |
+
config=args.config,
|
| 451 |
+
openpi_root=args.openpi_root,
|
| 452 |
+
norm_stats=args.norm_stats,
|
| 453 |
+
device=args.device,
|
| 454 |
+
num_denoise_steps=args.num_denoise_steps,
|
| 455 |
+
prompt=args.prompt,
|
| 456 |
+
model_dir=args.model_dir,
|
| 457 |
+
rotation_repr=args.rotation_repr,
|
| 458 |
+
image_key=args.image_key,
|
| 459 |
+
gripper_min=args.gripper_min,
|
| 460 |
+
gripper_max=args.gripper_max,
|
| 461 |
+
eef_extrinsic=eef_extrinsic,
|
| 462 |
+
upsample=args.upsample,
|
| 463 |
+
)
|
| 464 |
+
if args.selftest:
|
| 465 |
+
run_selftest(server)
|
| 466 |
+
else:
|
| 467 |
+
print("[ready] model loaded. import init_server/infer_target_eef from this module, "
|
| 468 |
+
"or pass --selftest to verify.", flush=True)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
if __name__ == "__main__":
|
| 472 |
+
main()
|
flexiv-umi-infer/umi_infer/codec/umi_spline.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Cubic-spline resampling of the decoded EEF target chunk before it is sent to the client.
|
| 3 |
+
|
| 4 |
+
The pi05 UMI policy emits a chunk of ``H`` (=50) absolute gripper-EEF targets at the
|
| 5 |
+
model's output step rate. A robot controller usually wants a *denser*, smooth trajectory
|
| 6 |
+
to track. This module resamples the chunk onto a finer uniform time grid with a proper
|
| 7 |
+
cubic spline:
|
| 8 |
+
|
| 9 |
+
position (xyz) -> scipy.interpolate.CubicSpline (C2, not-a-knot)
|
| 10 |
+
orientation (quat xyzw) -> scipy.spatial.transform.RotationSpline (C2 cubic on SO(3))
|
| 11 |
+
gripper (scalar) -> scipy.interpolate.PchipInterpolator (monotone, no overshoot)
|
| 12 |
+
|
| 13 |
+
Rotation is interpolated **on the SO(3) manifold**, NOT componentwise on the quaternion
|
| 14 |
+
(which would leave the unit sphere and distort the path / require ad-hoc renormalisation).
|
| 15 |
+
``RotationSpline`` builds a C2 curve minimising angular acceleration — the rotational
|
| 16 |
+
analogue of a cubic position spline. The gripper uses a shape-preserving PCHIP so the
|
| 17 |
+
interpolant never overshoots past the commanded open/close range (a plain cubic can ring).
|
| 18 |
+
|
| 19 |
+
The original ``H`` knots are reproduced exactly: with ``upsample=N`` the output grid is
|
| 20 |
+
``t = 0, 1/N, 2/N, ..., H-1`` (``(H-1)*N + 1`` samples), so every integer step — an
|
| 21 |
+
original model sample — lands on the grid and the splines pass through the raw poses there.
|
| 22 |
+
``num_out`` overrides this with an explicit sample count (still spanning ``[0, H-1]``).
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
from scipy.interpolate import CubicSpline, PchipInterpolator
|
| 29 |
+
from scipy.spatial.transform import Rotation, RotationSpline
|
| 30 |
+
|
| 31 |
+
__all__ = ["resample_pose_chunk", "num_samples_for"]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _canon_quat_xyzw(quat: np.ndarray) -> np.ndarray:
|
| 35 |
+
"""Unit-normalise and canonicalise [qx,qy,qz,qw] to qw >= 0 (matches umi_decode)."""
|
| 36 |
+
quat = np.asarray(quat, dtype=np.float32)
|
| 37 |
+
quat = quat / np.maximum(np.linalg.norm(quat, axis=-1, keepdims=True), 1e-8)
|
| 38 |
+
return np.where(quat[..., 3:4] < 0, -quat, quat).astype(np.float32)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def num_samples_for(horizon: int, upsample: int = 4, num_out: int | None = None) -> int:
|
| 42 |
+
"""How many samples ``resample_pose_chunk`` will emit for a given chunk (no compute).
|
| 43 |
+
|
| 44 |
+
Mirrors the same guards as ``resample_pose_chunk``: fewer than 2 knots, or a target
|
| 45 |
+
grid no denser than the chunk, is a no-op that returns the original ``horizon``.
|
| 46 |
+
"""
|
| 47 |
+
if horizon < 2:
|
| 48 |
+
return int(horizon)
|
| 49 |
+
m = int(num_out) if num_out is not None else max(int(upsample), 1) * (horizon - 1) + 1
|
| 50 |
+
return m if m > horizon else int(horizon)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def resample_pose_chunk(
|
| 54 |
+
pos: np.ndarray,
|
| 55 |
+
quat_xyzw: np.ndarray,
|
| 56 |
+
gripper: np.ndarray,
|
| 57 |
+
upsample: int = 4,
|
| 58 |
+
num_out: int | None = None,
|
| 59 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 60 |
+
"""Cubic-spline resample an EEF target chunk onto a denser uniform time grid.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
pos: (H, 3) absolute positions.
|
| 64 |
+
quat_xyzw: (H, 4) absolute orientations [qx, qy, qz, qw].
|
| 65 |
+
gripper: (H,) absolute gripper command.
|
| 66 |
+
upsample: int N; output has ``(H-1)*N + 1`` samples (each model step split into
|
| 67 |
+
N sub-steps). ``N <= 1`` disables resampling (inputs returned as-is).
|
| 68 |
+
num_out: optional explicit output sample count; overrides ``upsample``.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
pos_i (M, 3) float32 positions,
|
| 72 |
+
quat_i (M, 4) float32 orientations [qx,qy,qz,qw] (unit, qw >= 0),
|
| 73 |
+
grip_i (M,) float32 gripper command,
|
| 74 |
+
times (M,) float32 sample times in original-step units [0, H-1].
|
| 75 |
+
``M == H`` (inputs unchanged) when resampling is a no-op.
|
| 76 |
+
"""
|
| 77 |
+
pos = np.asarray(pos, dtype=np.float32)
|
| 78 |
+
quat_xyzw = _canon_quat_xyzw(quat_xyzw)
|
| 79 |
+
gripper = np.asarray(gripper, dtype=np.float32).reshape(-1)
|
| 80 |
+
horizon = pos.shape[0]
|
| 81 |
+
t_src = np.arange(horizon, dtype=np.float64)
|
| 82 |
+
|
| 83 |
+
m = num_samples_for(horizon, upsample, num_out)
|
| 84 |
+
|
| 85 |
+
# Need >=2 knots to spline, and no work if the target grid isn't denser than the chunk.
|
| 86 |
+
if horizon < 2 or m <= horizon:
|
| 87 |
+
return pos, quat_xyzw, gripper, t_src.astype(np.float32)
|
| 88 |
+
|
| 89 |
+
t_dst = np.linspace(0.0, horizon - 1.0, m)
|
| 90 |
+
pos_i = CubicSpline(t_src, pos, axis=0)(t_dst).astype(np.float32)
|
| 91 |
+
rots = Rotation.from_quat(quat_xyzw) # scipy quaternions are scalar-last [x,y,z,w]
|
| 92 |
+
quat_i = _canon_quat_xyzw(RotationSpline(t_src, rots)(t_dst).as_quat())
|
| 93 |
+
grip_i = PchipInterpolator(t_src, gripper)(t_dst).astype(np.float32)
|
| 94 |
+
return pos_i, quat_i, grip_i, t_dst.astype(np.float32)
|
flexiv-umi-infer/umi_infer/config.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared configuration for the policy server and robot agent."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from typing import List
|
| 7 |
+
|
| 8 |
+
# Max websocket frame size. Camera payloads can be large; give plenty of headroom.
|
| 9 |
+
MAX_WS_SIZE = 64 * 1024 * 1024
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class Config:
|
| 14 |
+
# Network
|
| 15 |
+
host: str = "0.0.0.0" # server bind address
|
| 16 |
+
port: int = 8765
|
| 17 |
+
|
| 18 |
+
# Control loop
|
| 19 |
+
control_rate_hz: float = 8.0 # cap on inference-request cadence (min interval
|
| 20 |
+
# between obs->chunk requests); the fixed-rate
|
| 21 |
+
# servo loop stays ON the robot, not over the network
|
| 22 |
+
servo_rate_hz: float = 100.0 # robot-side EEF servo publish rate (local executor)
|
| 23 |
+
control_mode: str = "eef_pose" # 'eef_pose' | 'joint'
|
| 24 |
+
|
| 25 |
+
# Trajectory chunking + inference pacing
|
| 26 |
+
# The policy returns a K-step chunk (eef_traj + dt); the robot executes it
|
| 27 |
+
# locally at servo_rate and only requests the next chunk on a trigger.
|
| 28 |
+
inference_mode: str = "sync" # 'sync' | 'async'
|
| 29 |
+
# sync : run the whole chunk, hold, grab FRESH obs,
|
| 30 |
+
# infer, run next (VLA always sees current state).
|
| 31 |
+
# async: refill at refill_at_fraction and overlap
|
| 32 |
+
# inference with the chunk tail (smoother, but
|
| 33 |
+
# the obs the VLA sees is slightly in the past).
|
| 34 |
+
chunk_size: int = 50 # K steps per chunk (mock uses this)
|
| 35 |
+
chunk_dt: float = 0.02 # seconds between chunk steps (50Hz native -> 1.0s/chunk)
|
| 36 |
+
refill_at_fraction: float = 0.7 # async only: request next chunk at this consumed fraction
|
| 37 |
+
settle_s: float = 0.0 # sync only: extra dwell after a chunk ends before grabbing obs
|
| 38 |
+
max_stale_s: float = 1.5 # executor holds the last pose this long with no new chunk,
|
| 39 |
+
# then stops publishing.
|
| 40 |
+
# MUST exceed worst-case inference+RTT or sync holds misfire.
|
| 41 |
+
|
| 42 |
+
# Cameras the agent reports (mock uses these as names)
|
| 43 |
+
cameras: List[str] = field(default_factory=lambda: ["left_wrist", "right_wrist"])
|
| 44 |
+
|
| 45 |
+
# Connection behavior (agent)
|
| 46 |
+
reconnect: bool = True
|
| 47 |
+
connect_timeout_s: float = 10.0
|
flexiv-umi-infer/umi_infer/export_E.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Export the policy-side extrinsic E of each arm from the URDF, with self-checks.
|
| 3 |
+
|
| 4 |
+
The policy convention is ``T_flange = T_cam @ E``:
|
| 5 |
+
T_flange = pose the robot reports (flange/TCP, shared world frame)
|
| 6 |
+
T_cam = the "end effector" of the dataset = the wrist camera optical frame
|
| 7 |
+
so ``E = T_cam_flange = inv(T_flange_cam)``. Re-run this after every URDF change.
|
| 8 |
+
|
| 9 |
+
The URDF camera pose is either CAD (identical on both arms relative to the gripper body) or
|
| 10 |
+
per-arm hand-eye calibrated (arms differ by a few mm). The source is recorded in E_from_urdf.json so a run can always
|
| 11 |
+
tell which one it used.
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python -m umi_infer.export_E --urdf <dual-arm URDF> [--out-dir data]
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from .robot_io import kin_flexiv as K
|
| 26 |
+
|
| 27 |
+
CAD, CALIBRATED = "cad", "calibrated"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
ap = argparse.ArgumentParser(description="export E = inv(T_flange_cam) from the URDF")
|
| 32 |
+
ap.add_argument("--urdf", default=K.URDF)
|
| 33 |
+
ap.add_argument("--out-dir", default=K.DATA_DIR)
|
| 34 |
+
a = ap.parse_args()
|
| 35 |
+
os.makedirs(a.out_dir, exist_ok=True)
|
| 36 |
+
print("URDF: %s camera link: %s" % (a.urdf, K.CAM_LINK))
|
| 37 |
+
|
| 38 |
+
summary = {"urdf": os.path.abspath(a.urdf), "cam_link": K.CAM_LINK, "sides": {}}
|
| 39 |
+
X, G = {}, {}
|
| 40 |
+
for side in ("left", "right"):
|
| 41 |
+
arm = K.Arm(side, urdf=a.urdf, robot=False, verbose=False) # FK only, no robot connection
|
| 42 |
+
X[side] = arm.T_flange_cam()
|
| 43 |
+
# Camera relative to the gripper body: equal on both arms for CAD values, even when the
|
| 44 |
+
# gripper is mounted at a different angle on each flange.
|
| 45 |
+
q0 = np.zeros(7)
|
| 46 |
+
G[side] = np.linalg.inv(arm.fk(q0, "grip_base_link")) @ arm.fk(q0, K.CAM_LINK)
|
| 47 |
+
E = np.linalg.inv(X[side])
|
| 48 |
+
resid = float(np.abs(X[side] @ E - np.eye(4)).max())
|
| 49 |
+
# The flange->camera transform must not depend on the joint angles.
|
| 50 |
+
drift_mm = float(np.abs(X[side] - arm.T_flange_cam(
|
| 51 |
+
np.radians([30., 60., -40., 100., 20., 80., -50.]))).max() * 1000)
|
| 52 |
+
if resid > 1e-9 or drift_mm > 1e-6:
|
| 53 |
+
raise SystemExit("%s: self-check failed (X*E-I %.2e, joint drift %.2e mm)" % (side, resid, drift_mm))
|
| 54 |
+
p = os.path.abspath(os.path.join(a.out_dir, "E_%s.npy" % side))
|
| 55 |
+
np.save(p, E.astype(np.float32))
|
| 56 |
+
t = X[side][:3, 3] * 1000
|
| 57 |
+
print("[%-5s] T_flange_cam t = [%+8.2f %+8.2f %+8.2f] mm -> %s" % (side, *t, p))
|
| 58 |
+
summary["sides"][side] = {"T_flange_cam": X[side].tolist(), "E_T_cam_flange": E.tolist(),
|
| 59 |
+
"t_flange_cam_mm": np.round(t, 3).tolist(), "npy": p}
|
| 60 |
+
|
| 61 |
+
diff_mm = float(np.linalg.norm(G["left"][:3, 3] - G["right"][:3, 3]) * 1000)
|
| 62 |
+
diff_deg = K.ang_between(G["left"][:3, :3], G["right"][:3, :3])
|
| 63 |
+
summary["camera_pose_source"] = CAD if diff_mm < 0.01 and diff_deg < 1e-3 else CALIBRATED
|
| 64 |
+
summary["two_arm_diff_mm"] = round(diff_mm, 4)
|
| 65 |
+
print("camera vs gripper body: arms differ by %.3f mm / %.3f deg -> camera pose source: %s"
|
| 66 |
+
% (diff_mm, diff_deg, summary["camera_pose_source"]))
|
| 67 |
+
j = os.path.join(a.out_dir, "E_from_urdf.json")
|
| 68 |
+
with open(j, "w") as f:
|
| 69 |
+
json.dump(summary, f, indent=1)
|
| 70 |
+
print("summary -> %s" % j)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
main()
|
flexiv-umi-infer/umi_infer/policies/__init__.py
ADDED
|
File without changes
|
flexiv-umi-infer/umi_infer/policies/base.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Policy interface. The real VLA model plugs in here."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from abc import ABC, abstractmethod
|
| 6 |
+
|
| 7 |
+
from ..protocol import Action, Observation
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Policy(ABC):
|
| 11 |
+
"""Maps an Observation to an Action.
|
| 12 |
+
|
| 13 |
+
SEAM: replace MockPolicy with your VLA here. ``infer`` runs inside the server's
|
| 14 |
+
asyncio handler, so if the model is heavy, run it in a thread/process executor
|
| 15 |
+
(the server can ``await loop.run_in_executor(...)``) to avoid blocking I/O.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def reset(self) -> None:
|
| 20 |
+
"""Reset any internal state (called when a client connects)."""
|
| 21 |
+
|
| 22 |
+
@abstractmethod
|
| 23 |
+
def infer(self, obs: Observation) -> Action:
|
| 24 |
+
"""Return the Action for this Observation (echo ``obs.seq`` into the Action)."""
|
flexiv-umi-infer/umi_infer/policies/flux_action_dual.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FLUX Action dual-hand UMI adapter for the existing msgpack policy server.
|
| 2 |
+
|
| 3 |
+
Input/output poses on the wire are xyzw flange poses. The FLUX training
|
| 4 |
+
representation uses wxyz camera/gripper poses; E maps data frame to flange.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from ..protocol import Action, Observation
|
| 19 |
+
from ..codec import umi_decode
|
| 20 |
+
from .base import Policy
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger("umi_infer.flux_action_dual")
|
| 23 |
+
SIDES = ("left", "right")
|
| 24 |
+
CAMERAS = ("images.left_ego", "images.right_ego")
|
| 25 |
+
# Frozen video VAE + text encoder: <dir>/video_vae.safetensors and <dir>/text_encoder/.
|
| 26 |
+
DEFAULT_RESOURCES = Path(os.environ.get("FLUX_RESOURCES", "weights/flux_resources"))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def validate_model_contract(config):
|
| 30 |
+
"""Accept only the verified 20-D UMI contract (flux-umi); never guess another channel layout."""
|
| 31 |
+
required = {"chunk_size": 32, "fps": 30, "camera_layout": "side_by_side",
|
| 32 |
+
"canvas_hw": [256, 512], "camera_keys": list(CAMERAS),
|
| 33 |
+
"torch_dtype": "bfloat16", "quantization": None,
|
| 34 |
+
"inference_profile": "default", "action_parameterization": "absolute"}
|
| 35 |
+
for key, expected in required.items():
|
| 36 |
+
value = config.get(key)
|
| 37 |
+
if isinstance(expected, list) and isinstance(value, tuple):
|
| 38 |
+
value = list(value)
|
| 39 |
+
if value != expected:
|
| 40 |
+
raise ValueError("unsupported FLUX UMI contract: " + key)
|
| 41 |
+
dim = config.get("action_dim")
|
| 42 |
+
if dim != 20 or config.get("gripper_flip_dims") or config.get("absolute_action_dims"):
|
| 43 |
+
raise ValueError("unsupported FLUX UMI action contract")
|
| 44 |
+
if config.get("cached_video_latents"):
|
| 45 |
+
raise ValueError("inference export must accept live images, not latent-cache training input")
|
| 46 |
+
for key in ("state_normalization", "action_normalization"):
|
| 47 |
+
stats = config.get(key) or {}
|
| 48 |
+
arrays = [np.asarray(stats.get(field), dtype=np.float64) for field in ("q01", "q99")]
|
| 49 |
+
if any(a.shape != (dim,) or not np.isfinite(a).all() for a in arrays):
|
| 50 |
+
raise ValueError("normalization shape/values do not match " + key)
|
| 51 |
+
if np.any(arrays[1] < arrays[0]):
|
| 52 |
+
raise ValueError("invalid quantile bounds")
|
| 53 |
+
return dim
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _pose_matrix(pose):
|
| 57 |
+
value = np.asarray(pose, dtype=np.float64)
|
| 58 |
+
if value.shape != (7,) or not np.isfinite(value).all() or np.any(np.abs(value) > np.finfo(np.float32).max):
|
| 59 |
+
raise ValueError("expected finite xyzw pose (7,)")
|
| 60 |
+
norm = np.linalg.norm(value[3:])
|
| 61 |
+
if norm < 1e-8:
|
| 62 |
+
raise ValueError("zero pose quaternion")
|
| 63 |
+
return umi_decode.pose_xyzw_to_matrix(value.astype(np.float32)).astype(np.float64)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _matrix_pose(transform):
|
| 67 |
+
transform = np.asarray(transform, dtype=np.float64)
|
| 68 |
+
quat = umi_decode.matrix_to_quat_xyzw(transform[:3, :3].astype(np.float32))
|
| 69 |
+
return np.r_[transform[:3, 3], quat].astype(np.float32)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _extrinsic(spec):
|
| 73 |
+
if spec is None:
|
| 74 |
+
return np.eye(4, dtype=np.float64)
|
| 75 |
+
path = Path(spec)
|
| 76 |
+
if not path.is_file():
|
| 77 |
+
raise FileNotFoundError(f"extrinsic file not found: {path}")
|
| 78 |
+
e = np.asarray(np.load(path, allow_pickle=False), dtype=np.float64)
|
| 79 |
+
if (e.shape != (4, 4) or not np.isfinite(e).all()
|
| 80 |
+
or np.any(np.abs(e) > np.finfo(np.float32).max)):
|
| 81 |
+
raise ValueError(f"invalid extrinsic: {path}")
|
| 82 |
+
if not np.allclose(e[3], [0, 0, 0, 1], atol=1e-6) or not np.allclose(
|
| 83 |
+
e[:3, :3].T @ e[:3, :3], np.eye(3), atol=1e-4
|
| 84 |
+
) or not np.isclose(np.linalg.det(e[:3, :3]), 1.0, atol=1e-4):
|
| 85 |
+
raise ValueError(f"extrinsic is not a rigid transform: {path}")
|
| 86 |
+
return e
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def validate_extrinsics(left, right, provenance=None):
|
| 90 |
+
"""Require both flange extrinsics and check them against their saved URDF export."""
|
| 91 |
+
specs = {"left": left, "right": right}
|
| 92 |
+
if not all(specs.values()):
|
| 93 |
+
raise ValueError("FLUX needs E_LEFT and E_RIGHT; identity is only for offline tests")
|
| 94 |
+
matrices = {side: _extrinsic(path) for side, path in specs.items()}
|
| 95 |
+
if provenance is not None:
|
| 96 |
+
record = json.loads(Path(provenance).read_text())
|
| 97 |
+
if record.get("camera_pose_source") not in ("cad", "calibrated"):
|
| 98 |
+
raise ValueError("unknown E provenance: " + str(provenance))
|
| 99 |
+
urdf = Path(record["urdf"])
|
| 100 |
+
if not urdf.is_file() or urdf.stat().st_mtime_ns > Path(provenance).stat().st_mtime_ns:
|
| 101 |
+
raise ValueError("E provenance is older than or missing its URDF")
|
| 102 |
+
for side in SIDES:
|
| 103 |
+
saved = record["sides"][side]
|
| 104 |
+
if Path(saved["npy"]).resolve() != Path(specs[side]).resolve():
|
| 105 |
+
raise ValueError(f"{side} E path differs from URDF export")
|
| 106 |
+
if not np.allclose(matrices[side], saved["E_T_cam_flange"], rtol=0, atol=1e-6):
|
| 107 |
+
raise ValueError(f"{side} E differs from URDF export")
|
| 108 |
+
return matrices
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def encode_state(current, previous, gripper, e_inv):
|
| 112 |
+
"""Mirror relative_hand(current, previous), using the current gripper."""
|
| 113 |
+
cur = _pose_matrix(current) @ e_inv
|
| 114 |
+
prev = _pose_matrix(previous) @ e_inv
|
| 115 |
+
if not np.isfinite(gripper) or abs(gripper) > np.finfo(np.float32).max:
|
| 116 |
+
raise ValueError("invalid gripper")
|
| 117 |
+
relative = np.linalg.inv(cur) @ prev
|
| 118 |
+
state = np.r_[relative[:3, 3], relative[:3, 0], relative[:3, 1], gripper].astype(np.float32)
|
| 119 |
+
if not np.isfinite(state).all():
|
| 120 |
+
raise ValueError("FLUX state overflowed during coordinate conversion")
|
| 121 |
+
return state, cur
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def decode_targets(anchor, relative, e):
|
| 125 |
+
"""Invert the training's column-ordered rot6d and map targets to flange."""
|
| 126 |
+
values = np.asarray(relative, dtype=np.float64)
|
| 127 |
+
if (values.ndim != 2 or values.shape[1] != 10 or not np.isfinite(values).all()
|
| 128 |
+
or np.any(np.abs(values) > np.finfo(np.float32).max)):
|
| 129 |
+
raise ValueError("expected finite (steps, 10) targets")
|
| 130 |
+
a, b = values[:, 3:6], values[:, 6:9]
|
| 131 |
+
norm_a = np.linalg.norm(a, axis=-1, keepdims=True)
|
| 132 |
+
if np.any(norm_a < 1e-8):
|
| 133 |
+
raise ValueError("degenerate first rotation column")
|
| 134 |
+
a = a / norm_a
|
| 135 |
+
b = b - (a * b).sum(-1, keepdims=True) * a
|
| 136 |
+
norm_b = np.linalg.norm(b, axis=-1, keepdims=True)
|
| 137 |
+
if np.any(norm_b < 1e-8):
|
| 138 |
+
raise ValueError("degenerate second rotation column")
|
| 139 |
+
b = b / norm_b
|
| 140 |
+
transforms = np.broadcast_to(np.eye(4), (len(values), 4, 4)).copy()
|
| 141 |
+
transforms[:, :3, 3] = values[:, :3]
|
| 142 |
+
transforms[:, :3, :3] = np.stack((a, b, np.cross(a, b)), axis=-1)
|
| 143 |
+
absolute = anchor @ transforms @ e
|
| 144 |
+
poses = np.stack([_matrix_pose(t) for t in absolute])
|
| 145 |
+
grippers = values[:, 9].astype(np.float32)
|
| 146 |
+
if not np.isfinite(poses).all() or not np.isfinite(grippers).all():
|
| 147 |
+
raise ValueError("FLUX targets overflowed during coordinate conversion")
|
| 148 |
+
return poses, grippers
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def decode_yuv420p(frame, size=(256, 256)):
|
| 152 |
+
"""I420 planes -> RGB via the same call the training cache uses:
|
| 153 |
+
pyav ``to_ndarray(rgb24, width, height)``. pyav ignores color tags
|
| 154 |
+
(bt709/601, tv/pc), so identical planes give bit-identical pixels."""
|
| 155 |
+
import av
|
| 156 |
+
|
| 157 |
+
h, w = int(frame.height), int(frame.width)
|
| 158 |
+
if h <= 0 or w <= 0 or h % 2 or w % 2 or len(frame.data) != h * w * 3 // 2:
|
| 159 |
+
raise ValueError("invalid yuv420p wrist frame")
|
| 160 |
+
planes = np.frombuffer(frame.data, np.uint8).reshape(h * 3 // 2, w)
|
| 161 |
+
video = av.VideoFrame.from_ndarray(planes, format="yuv420p")
|
| 162 |
+
height, width = size
|
| 163 |
+
return video.to_ndarray(format="rgb24", width=width, height=height)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def decode_image(frame, size=(256, 256)):
|
| 167 |
+
"""Match the training ffmpeg bilinear scale and RGB24 pixel conversion."""
|
| 168 |
+
if frame is not None and frame.format == "yuv420p":
|
| 169 |
+
return decode_yuv420p(frame, size)
|
| 170 |
+
from io import BytesIO
|
| 171 |
+
import subprocess
|
| 172 |
+
|
| 173 |
+
from PIL import Image, UnidentifiedImageError
|
| 174 |
+
|
| 175 |
+
if frame is None or frame.format != "jpeg" or not frame.data:
|
| 176 |
+
raise ValueError("FLUX requires a JPEG or yuv420p wrist frame")
|
| 177 |
+
if frame.height <= 0 or frame.width <= 0:
|
| 178 |
+
raise ValueError("invalid wrist frame dimensions")
|
| 179 |
+
try:
|
| 180 |
+
with Image.open(BytesIO(frame.data)) as image:
|
| 181 |
+
if image.size != (frame.width, frame.height):
|
| 182 |
+
raise ValueError("JPEG dimensions disagree with wire frame")
|
| 183 |
+
except (UnidentifiedImageError, OSError) as exc:
|
| 184 |
+
raise ValueError("invalid wrist JPEG") from exc
|
| 185 |
+
height, width = size
|
| 186 |
+
result = subprocess.run(
|
| 187 |
+
["ffmpeg", "-nostdin", "-v", "error", "-threads", "1", "-filter_threads", "1",
|
| 188 |
+
"-f", "mjpeg", "-i", "pipe:0", "-frames:v", "1", "-fps_mode", "passthrough",
|
| 189 |
+
"-vf", f"scale={width}:{height}:flags=bilinear", "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"],
|
| 190 |
+
input=frame.data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10, check=True,
|
| 191 |
+
)
|
| 192 |
+
if len(result.stdout) != height * width * 3:
|
| 193 |
+
raise ValueError("wrist JPEG did not decode to the training frame size")
|
| 194 |
+
return np.frombuffer(result.stdout, dtype=np.uint8).reshape(height, width, 3)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _prewarm_context(policy, prompt, device, cpu_contexts=None):
|
| 198 |
+
"""Never allow a cache miss to move the 4B encoder onto the occupied GPU."""
|
| 199 |
+
import torch
|
| 200 |
+
from flux_action.models.text_encoder import text_contexts
|
| 201 |
+
from flux_action.processing import packing
|
| 202 |
+
from flux_action.policy import VEC_DIM
|
| 203 |
+
|
| 204 |
+
policy.reset()
|
| 205 |
+
captions = [prompt, ""] if prompt else [""]
|
| 206 |
+
if cpu_contexts is None:
|
| 207 |
+
if policy.device.type != "cpu":
|
| 208 |
+
raise RuntimeError("prewarm before moving FLUX DiT to GPU")
|
| 209 |
+
if any(p.device.type != "cpu" for p in policy.text_encoder.parameters()):
|
| 210 |
+
raise RuntimeError("text encoder must remain on CPU during prewarm")
|
| 211 |
+
cpu_contexts = text_contexts(policy.text_encoder, captions, torch.device("cpu"))
|
| 212 |
+
policy.set_text_encoder_offload(True)
|
| 213 |
+
if policy.device != torch.device(device):
|
| 214 |
+
policy.to(device)
|
| 215 |
+
policy.eval()
|
| 216 |
+
for caption, context in zip(captions, cpu_contexts, strict=True):
|
| 217 |
+
context = context.to(device=device, dtype=policy.dtype_)
|
| 218 |
+
policy._ctx_cache[caption] = (context, packing.pack_text(context, VEC_DIM)["ctx_ids"])
|
| 219 |
+
if not all(c in policy._ctx_cache and policy._ctx_cache[c][0].device == torch.device(device)
|
| 220 |
+
for c in captions):
|
| 221 |
+
raise RuntimeError("FLUX caption cache prewarm failed; refusing GPU encoder fallback")
|
| 222 |
+
return tuple(captions), cpu_contexts
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class FluxActionDualPolicy(Policy):
|
| 226 |
+
def __init__(self, *, export_dir, source_dir=None, prompt="fold the clothes", device="cuda:0",
|
| 227 |
+
resources_dir=DEFAULT_RESOURCES, extrinsics=None, image_keys=None,
|
| 228 |
+
action_horizon=0, sampler="euler", steps=4, shift=5.0,
|
| 229 |
+
guidance=1.0, action_guidance=1.0, seed=0, model=None, e_provenance=None):
|
| 230 |
+
import torch
|
| 231 |
+
|
| 232 |
+
if model is None:
|
| 233 |
+
validate_model_contract(json.loads((Path(export_dir) / "config.json").read_text()))
|
| 234 |
+
# Optional flux_action source tree; by default the installed package is used.
|
| 235 |
+
if source_dir and str(source_dir) not in sys.path:
|
| 236 |
+
sys.path.insert(0, str(source_dir))
|
| 237 |
+
self.device = torch.device(device)
|
| 238 |
+
self.prompt = str(prompt)
|
| 239 |
+
if not self.prompt:
|
| 240 |
+
raise ValueError("FLUX task prompt must not be empty")
|
| 241 |
+
self.image_keys = image_keys or {"left": "left_wrist", "right": "right_wrist"}
|
| 242 |
+
if any(not self.image_keys.get(s) for s in SIDES):
|
| 243 |
+
raise ValueError("both wrist camera keys are required")
|
| 244 |
+
self.e = validate_extrinsics((extrinsics or {}).get("left"),
|
| 245 |
+
(extrinsics or {}).get("right"), e_provenance)
|
| 246 |
+
self.e_inv = {s: np.linalg.inv(self.e[s]) for s in SIDES}
|
| 247 |
+
self.horizon = int(action_horizon)
|
| 248 |
+
if not 0 <= self.horizon <= 32:
|
| 249 |
+
raise ValueError("action horizon must be 0..32")
|
| 250 |
+
if model is None:
|
| 251 |
+
from flux_action.models.text_encoder import load_text_encoder
|
| 252 |
+
from flux_action.models.video_vae import load_video_vae
|
| 253 |
+
from flux_action.policy import FluxActionPolicy
|
| 254 |
+
|
| 255 |
+
resources = Path(resources_dir)
|
| 256 |
+
vae = load_video_vae(str(resources / "video_vae.safetensors"))
|
| 257 |
+
encoder = load_text_encoder(str(resources / "text_encoder"))
|
| 258 |
+
model = FluxActionPolicy.from_pretrained(export_dir, video_vae=vae,
|
| 259 |
+
text_encoder=encoder, device="cpu")
|
| 260 |
+
self.model = model
|
| 261 |
+
cfg = model.config
|
| 262 |
+
self.action_dim = validate_model_contract(cfg.to_dict())
|
| 263 |
+
if cfg.torch_dtype != "bfloat16" or cfg.quantization is not None:
|
| 264 |
+
raise ValueError("FLUX UMI requires unquantized bfloat16 export")
|
| 265 |
+
if list(cfg.camera_order) != list(CAMERAS) or tuple(cfg.canvas_hw) != (256, 512):
|
| 266 |
+
raise ValueError("FLUX export camera contract differs from cloth-folding UMI")
|
| 267 |
+
if cfg.action_parameterization != "absolute" or list(cfg.gripper_flip_dims):
|
| 268 |
+
raise ValueError("FLUX export action contract differs from cloth-folding UMI")
|
| 269 |
+
if cfg.inference_profile != "default" or cfg.state_normalization is None or cfg.action_normalization is None:
|
| 270 |
+
raise ValueError("FLUX export lacks the UMI default profile or dataset statistics")
|
| 271 |
+
from flux_action.config import PolicyConfig
|
| 272 |
+
cfg = PolicyConfig(**{**cfg.to_dict(), "sampler": sampler,
|
| 273 |
+
"num_inference_steps": steps, "sampler_shift": shift,
|
| 274 |
+
"guidance_scale": guidance, "guidance_scale_action": action_guidance,
|
| 275 |
+
"inference_seed": seed})
|
| 276 |
+
cfg.validate_inference()
|
| 277 |
+
model.config = cfg
|
| 278 |
+
self.settings = {"sampler": sampler, "steps": steps, "shift": shift,
|
| 279 |
+
"guidance": guidance, "action_guidance": action_guidance, "seed": seed}
|
| 280 |
+
self.dt = 1.0 / cfg.fps
|
| 281 |
+
self._captions = ()
|
| 282 |
+
self._cpu_contexts = None
|
| 283 |
+
if self.device.type == "cuda" and hasattr(model, "text_encoder"):
|
| 284 |
+
# CPU encode before uploading the DiT, then seed the cache after .to() clears it.
|
| 285 |
+
self._captions, self._cpu_contexts = _prewarm_context(self.model, prompt, self.device)
|
| 286 |
+
elif self.device.type == "cuda":
|
| 287 |
+
raise ValueError("CUDA FLUX requires an encoder with a verifiable offload cache")
|
| 288 |
+
else:
|
| 289 |
+
self.model.to(self.device).eval()
|
| 290 |
+
self.model.reset()
|
| 291 |
+
log.info("FLUX UMI ready: export=%s settings=%s device=%s E=%s (frame equivalence unverified)",
|
| 292 |
+
export_dir, self.settings, self.device, {s: self.e[s].tolist() for s in SIDES})
|
| 293 |
+
|
| 294 |
+
def reset(self):
|
| 295 |
+
if self._captions:
|
| 296 |
+
self._captions, self._cpu_contexts = _prewarm_context(
|
| 297 |
+
self.model, self.prompt, self.device, self._cpu_contexts
|
| 298 |
+
)
|
| 299 |
+
else:
|
| 300 |
+
self.model.reset()
|
| 301 |
+
|
| 302 |
+
def infer(self, obs: Observation) -> Action:
|
| 303 |
+
import torch
|
| 304 |
+
|
| 305 |
+
batch = {"task": [self.prompt]}
|
| 306 |
+
anchors = {}
|
| 307 |
+
prev_sources = {}
|
| 308 |
+
states = []
|
| 309 |
+
for side, key in zip(SIDES, CAMERAS, strict=True):
|
| 310 |
+
image = decode_image((obs.images or {}).get(self.image_keys[side]))
|
| 311 |
+
batch[key] = torch.from_numpy(image.copy()).permute(2, 0, 1)[None].to(
|
| 312 |
+
device=self.device, dtype=torch.float32) / 255.0
|
| 313 |
+
current = (obs.eef or {}).get(side)
|
| 314 |
+
previous = (obs.eef_prev or {}).get(side)
|
| 315 |
+
prev_sources[side] = "obs" if previous is not None else "current"
|
| 316 |
+
if previous is None:
|
| 317 |
+
previous = current
|
| 318 |
+
gripper = (obs.gripper or {}).get(side)
|
| 319 |
+
if gripper is None:
|
| 320 |
+
raise ValueError(f"missing {side} gripper")
|
| 321 |
+
state, anchors[side] = encode_state(current, previous, float(gripper), self.e_inv[side])
|
| 322 |
+
states.append(state)
|
| 323 |
+
batch["state"] = torch.from_numpy(np.concatenate(states)[None]).to(self.device)
|
| 324 |
+
if self._captions and any(
|
| 325 |
+
c not in self.model._ctx_cache or self.model._ctx_cache[c][0].device != self.device
|
| 326 |
+
for c in self._captions
|
| 327 |
+
):
|
| 328 |
+
raise RuntimeError("FLUX text cache missing; refusing GPU encoder fallback")
|
| 329 |
+
started = time.perf_counter()
|
| 330 |
+
with torch.no_grad():
|
| 331 |
+
output = self.model.predict_action_chunk(batch)
|
| 332 |
+
values = output.detach().float().cpu().numpy()
|
| 333 |
+
if values.shape != (1, 32, self.action_dim) or not np.isfinite(values).all():
|
| 334 |
+
raise ValueError("invalid FLUX action output")
|
| 335 |
+
keep = self.horizon or 32
|
| 336 |
+
trajectories, grippers = {}, {}
|
| 337 |
+
for hand, side in enumerate(SIDES):
|
| 338 |
+
offset = hand * 10
|
| 339 |
+
poses, grip = decode_targets(anchors[side], values[0, :keep, offset:offset+10],
|
| 340 |
+
self.e[side])
|
| 341 |
+
trajectories[side] = poses.tolist()
|
| 342 |
+
grippers[side] = grip.tolist()
|
| 343 |
+
log.info("FLUX seq=%s steps=%d ms=%.0f prev=%s", obs.seq, keep,
|
| 344 |
+
(time.perf_counter() - started) * 1000, prev_sources)
|
| 345 |
+
return Action(seq=obs.seq, stamp=time.time(), control="eef_pose",
|
| 346 |
+
eef_target={s: trajectories[s][0] for s in SIDES},
|
| 347 |
+
gripper={s: grippers[s][0] for s in SIDES},
|
| 348 |
+
eef_traj=trajectories, gripper_traj=grippers, dt=self.dt,
|
| 349 |
+
extra={"policy": "flux", "n_steps": keep, "prev_src": prev_sources,
|
| 350 |
+
"sampler": self.settings, "action_dim": self.action_dim})
|
flexiv-umi-infer/umi_infer/policies/mock.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mock policy: stands in for the VLA so we can exercise the comm end-to-end.
|
| 2 |
+
|
| 3 |
+
Modes:
|
| 4 |
+
- hold : echo the observed pose.
|
| 5 |
+
- wobble : hold + small sinusoid on the right EEF z.
|
| 6 |
+
- zero : send an all-zero pose.
|
| 7 |
+
- traj : a scripted dual-arm up/down EE trajectory with gripper commands.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import math
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from ..protocol import Action, Observation
|
| 16 |
+
from .base import Policy
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MockPolicy(Policy):
|
| 20 |
+
"""Returns a safe, predictable Action.
|
| 21 |
+
|
| 22 |
+
modes:
|
| 23 |
+
- ``hold`` : echo the observed EEF pose as the target (no commanded motion).
|
| 24 |
+
Safe default — useful to confirm the round-trip without moving.
|
| 25 |
+
- ``wobble`` : hold, plus a small sinusoid added to the right EEF z. Proves the
|
| 26 |
+
loop is closed (the agent's next observation should follow it).
|
| 27 |
+
- ``zero`` : send an all-zero pose. NEVER use on hardware; for wire tests only.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
mode: str = "hold",
|
| 33 |
+
wobble_amp_m: float = 0.02,
|
| 34 |
+
wobble_hz: float = 0.25,
|
| 35 |
+
traj_offset_m: float = 0.06,
|
| 36 |
+
traj_hold_sec: float = 0.5,
|
| 37 |
+
traj_move_up_sec: float = 2.0,
|
| 38 |
+
traj_move_down_sec: float = 2.0,
|
| 39 |
+
chunk_size: int = 50,
|
| 40 |
+
chunk_dt: float = 0.02,
|
| 41 |
+
):
|
| 42 |
+
self.mode = mode
|
| 43 |
+
self.amp = wobble_amp_m
|
| 44 |
+
self.hz = wobble_hz
|
| 45 |
+
self.traj_offset_m = traj_offset_m
|
| 46 |
+
self.traj_hold_sec = traj_hold_sec
|
| 47 |
+
self.traj_move_up_sec = traj_move_up_sec
|
| 48 |
+
self.traj_move_down_sec = traj_move_down_sec
|
| 49 |
+
# trajectory chunk shape: each infer() returns chunk_size future steps spaced chunk_dt
|
| 50 |
+
self.chunk_size = max(1, int(chunk_size))
|
| 51 |
+
self.chunk_dt = float(chunk_dt)
|
| 52 |
+
self._t0 = time.time()
|
| 53 |
+
|
| 54 |
+
def reset(self) -> None:
|
| 55 |
+
self._t0 = time.time()
|
| 56 |
+
|
| 57 |
+
def infer(self, obs: Observation) -> Action:
|
| 58 |
+
# Build a chunk of chunk_size future steps spaced chunk_dt, starting "now".
|
| 59 |
+
now = max(0.0, time.time() - self._t0)
|
| 60 |
+
dt = self.chunk_dt
|
| 61 |
+
eef_traj: dict = {}
|
| 62 |
+
gripper_traj: dict = {}
|
| 63 |
+
for i in range(self.chunk_size):
|
| 64 |
+
eef_i, grip_i = self._sample(obs, now + i * dt)
|
| 65 |
+
for side, pose in eef_i.items():
|
| 66 |
+
eef_traj.setdefault(side, []).append(pose)
|
| 67 |
+
for side, g in grip_i.items():
|
| 68 |
+
gripper_traj.setdefault(side, []).append(float(g))
|
| 69 |
+
|
| 70 |
+
# length-1 fallback fields (first step) so single-pose consumers still work
|
| 71 |
+
eef_target = {side: seq[0] for side, seq in eef_traj.items() if seq}
|
| 72 |
+
gripper = {side: seq[0] for side, seq in gripper_traj.items() if seq}
|
| 73 |
+
|
| 74 |
+
return Action(
|
| 75 |
+
seq=obs.seq,
|
| 76 |
+
stamp=time.time(),
|
| 77 |
+
control="eef_pose",
|
| 78 |
+
eef_target=eef_target,
|
| 79 |
+
gripper=gripper,
|
| 80 |
+
eef_traj=eef_traj,
|
| 81 |
+
gripper_traj=gripper_traj,
|
| 82 |
+
dt=dt,
|
| 83 |
+
extra={"policy": "mock", "mode": self.mode, "chunk": self.chunk_size, "dt": dt},
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def _sample(self, obs: Observation, t: float):
|
| 87 |
+
"""Return (eef:{side:[7]}, gripper:{side:float}) for the mode at elapsed time t."""
|
| 88 |
+
eef = {side: list(pose) for side, pose in obs.eef.items() if pose and len(pose) >= 3}
|
| 89 |
+
gripper = dict(obs.gripper)
|
| 90 |
+
|
| 91 |
+
if self.mode == "wobble":
|
| 92 |
+
r = eef.get("right")
|
| 93 |
+
if r and len(r) >= 3:
|
| 94 |
+
r[2] += self.amp * math.sin(2 * math.pi * self.hz * t)
|
| 95 |
+
elif self.mode == "zero":
|
| 96 |
+
eef = {side: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] for side in obs.eef}
|
| 97 |
+
elif self.mode == "traj":
|
| 98 |
+
dz, gripper = self._traj_dz_gripper(t)
|
| 99 |
+
for side, pose in eef.items():
|
| 100 |
+
if len(pose) == 7:
|
| 101 |
+
pose[2] += dz
|
| 102 |
+
# "hold" (default): echo current pose/gripper unchanged
|
| 103 |
+
return eef, gripper
|
| 104 |
+
|
| 105 |
+
def _traj_dz_gripper(self, t: float):
|
| 106 |
+
"""The dual-arm up/hold/down dz curve + per-phase gripper at elapsed time t."""
|
| 107 |
+
t = max(0.0, t)
|
| 108 |
+
hold = self.traj_hold_sec
|
| 109 |
+
move_up = self.traj_move_up_sec
|
| 110 |
+
move_down = self.traj_move_down_sec
|
| 111 |
+
total = hold + move_up + hold + move_down
|
| 112 |
+
|
| 113 |
+
if t < hold:
|
| 114 |
+
return 0.0, {"left": 0.0, "right": 0.0}
|
| 115 |
+
if t < hold + move_up:
|
| 116 |
+
s = (t - hold) / move_up if move_up > 0 else 1.0
|
| 117 |
+
return self.traj_offset_m * _smoothstep(s), {"left": 1.0, "right": 0.0}
|
| 118 |
+
if t < hold + move_up + hold:
|
| 119 |
+
return self.traj_offset_m, {"left": 1.0, "right": 1.0}
|
| 120 |
+
if t < total:
|
| 121 |
+
s = (t - hold - move_up - hold) / move_down if move_down > 0 else 1.0
|
| 122 |
+
return self.traj_offset_m * (1.0 - _smoothstep(s)), {"left": 0.0, "right": 1.0}
|
| 123 |
+
return 0.0, {"left": 0.0, "right": 0.0}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _smoothstep(s: float) -> float:
|
| 127 |
+
s = max(0.0, min(1.0, s))
|
| 128 |
+
return s * s * (3.0 - 2.0 * s)
|
flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dual-hand pi05 UMI policy (robot-agnostic; config given by --config).
|
| 2 |
+
|
| 3 |
+
Per inference cycle:
|
| 4 |
+
|
| 5 |
+
obs (both wrist images + per-side [prev,cur] hand pose + gripper, dataset scale)
|
| 6 |
+
-> E^-1 hop per side (robot hand frame -> data gripper/camera frame G)
|
| 7 |
+
-> umi_infer.codec.umi_pi05_server.infer_target_eef (num_hands=2)
|
| 8 |
+
-> per-side absolute G-frame target chunks (anchored at each side's current pose)
|
| 9 |
+
-> E hop back per side -> Action.eef_traj/gripper_traj {"left":..., "right":...}
|
| 10 |
+
|
| 11 |
+
Image sources per side: 'live' decodes obs.images[<side>_wrist]; 'replay' plays a
|
| 12 |
+
dataset episode video; 'auto' prefers live. episode_parquet switches BOTH proprio
|
| 13 |
+
sides to open-loop dataset state[16] rows (DRY-RUN model-reproduction mode: targets
|
| 14 |
+
are anchored in the dataset world frame, not the robot base).
|
| 15 |
+
|
| 16 |
+
Flexiv: this file only deals with ``obs.eef`` (reported hand pose, xyzw) and E.
|
| 17 |
+
* robot_io/flexiv.py reports the flange/TCP pose in the shared world frame,
|
| 18 |
+
already converted from Flexiv's native wxyz to xyzw.
|
| 19 |
+
* E = inv(T_flange_cam), exported from the URDF by umi_infer/export_E.py
|
| 20 |
+
(hand-eye calibration is baked into the URDF).
|
| 21 |
+
* Hence T_G = obs.eef @ E^-1 = T_world_cam, the frame of camera-pose datasets.
|
| 22 |
+
|
| 23 |
+
Quaternion column order vs config.pose_format is handled in umi_pi05_server;
|
| 24 |
+
everything in this file is xyzw.
|
| 25 |
+
|
| 26 |
+
VLA_QUAT_PERM (default off)
|
| 27 |
+
---------------------------
|
| 28 |
+
Legacy workaround for checkpoints trained on wxyz labels read as xyzw (i.e. with
|
| 29 |
+
pose_format=xyz_quat_xyzw on wxyz data), which trains in a permuted rotation space.
|
| 30 |
+
That misread map P is not a group homomorphism, but it is a bijection on SO(3), so it
|
| 31 |
+
can be compensated at deployment:
|
| 32 |
+
in: re-anchor poses to the session's first frame, then use the true wxyz as xyzw
|
| 33 |
+
out: invert the permutation, then undo the re-anchoring
|
| 34 |
+
Re-anchoring is required: since P is not a homomorphism, relative quantities in the
|
| 35 |
+
misread space depend on the reference frame. This only fixes the pipeline, not the
|
| 36 |
+
distorted geometry the model learned; the real fix is re-exporting and retraining.
|
| 37 |
+
|
| 38 |
+
Do not guess this switch from the checkpoint path; ``_quat_perm_advice()`` checks the
|
| 39 |
+
checkpoint's own config. pose_format=xyz_quat_wxyz means it was read correctly at
|
| 40 |
+
training time, so QUAT_PERM must be off.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
from __future__ import annotations
|
| 44 |
+
|
| 45 |
+
import logging
|
| 46 |
+
import os
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
import time
|
| 49 |
+
|
| 50 |
+
import cv2
|
| 51 |
+
import numpy as np
|
| 52 |
+
|
| 53 |
+
from ..protocol import Action, Observation
|
| 54 |
+
from .base import Policy
|
| 55 |
+
|
| 56 |
+
log = logging.getLogger("umi_infer.umi_pi05_dual")
|
| 57 |
+
|
| 58 |
+
SIDES = ("left", "right")
|
| 59 |
+
POSE_SLICES = {"left": (0, 7), "right": (8, 15)} # merged dual-hand flat state[16]
|
| 60 |
+
GRIP_INDEX = {"left": 7, "right": 15}
|
| 61 |
+
# Default off; set to 1 only for checkpoints trained on misread wxyz labels (see module doc).
|
| 62 |
+
QUAT_PERM = os.environ.get("VLA_QUAT_PERM", "0") == "1"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _quat_perm_advice(checkpoint_dir) -> None:
|
| 66 |
+
"""Check VLA_QUAT_PERM against the checkpoint's metadata.pt and warn if it looks wrong.
|
| 67 |
+
|
| 68 |
+
pose_format == xyz_quat_wxyz -> read correctly at training time -> perm must be off
|
| 69 |
+
pose_format == xyz_quat_xyzw -> perm needed only if the data was actually wxyz;
|
| 70 |
+
the config alone cannot tell, so only advise.
|
| 71 |
+
If metadata.pt is unreadable, say so and do not guess.
|
| 72 |
+
"""
|
| 73 |
+
md = Path(checkpoint_dir) / "metadata.pt"
|
| 74 |
+
pf = None
|
| 75 |
+
if md.exists():
|
| 76 |
+
try:
|
| 77 |
+
import torch
|
| 78 |
+
pf = torch.load(md, map_location="cpu", weights_only=False)[
|
| 79 |
+
"config"]["data"].get("pose_format")
|
| 80 |
+
except Exception as e: # noqa: BLE001
|
| 81 |
+
log.warning("failed to read %s (%s); cannot verify VLA_QUAT_PERM", md, e)
|
| 82 |
+
return
|
| 83 |
+
else:
|
| 84 |
+
log.warning("%s not found; cannot verify VLA_QUAT_PERM", md)
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
if pf == "xyz_quat_wxyz":
|
| 88 |
+
if QUAT_PERM:
|
| 89 |
+
log.error("VLA_QUAT_PERM=1 but this checkpoint has pose_format=xyz_quat_wxyz; "
|
| 90 |
+
"it was trained reading wxyz correctly, so the permutation corrupts orientation. "
|
| 91 |
+
"Unset VLA_QUAT_PERM.")
|
| 92 |
+
else:
|
| 93 |
+
log.info("VLA_QUAT_PERM=0 matches checkpoint (pose_format=xyz_quat_wxyz, "
|
| 94 |
+
"column order handled by umi_pi05_server per config)")
|
| 95 |
+
elif pf == "xyz_quat_xyzw":
|
| 96 |
+
log.info("checkpoint pose_format=xyz_quat_xyzw, VLA_QUAT_PERM=%s. "
|
| 97 |
+
"Enable only if the training data was wxyz but read as xyzw; "
|
| 98 |
+
"leave off if the data really is xyzw.", int(QUAT_PERM))
|
| 99 |
+
else:
|
| 100 |
+
log.warning("unknown checkpoint pose_format=%r; verify VLA_QUAT_PERM=%s manually",
|
| 101 |
+
pf, int(QUAT_PERM))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _decode_video_frames(path: Path) -> list:
|
| 105 |
+
cap = cv2.VideoCapture(str(path))
|
| 106 |
+
frames = []
|
| 107 |
+
while True:
|
| 108 |
+
ok, bgr = cap.read()
|
| 109 |
+
if not ok:
|
| 110 |
+
break
|
| 111 |
+
frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
|
| 112 |
+
cap.release()
|
| 113 |
+
if not frames:
|
| 114 |
+
raise RuntimeError(f"no frames decoded from {path}")
|
| 115 |
+
return frames
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class UmiPi05DualPolicy(Policy):
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
checkpoint_dir: str,
|
| 122 |
+
config: str = "pi05_umi_v3",
|
| 123 |
+
openpi_root: str | None = None,
|
| 124 |
+
device: str = "cuda:0",
|
| 125 |
+
prompt: str = "fold the clothes",
|
| 126 |
+
upsample: int = 1,
|
| 127 |
+
chunk_fps: float = 30.0,
|
| 128 |
+
num_denoise_steps: int = 10,
|
| 129 |
+
action_horizon: int = 0,
|
| 130 |
+
episode_videos: "dict[str, str] | None" = None, # side -> mp4 (replay/auto fallback)
|
| 131 |
+
episode_parquet: str | None = None, # open-loop proprio (DRY-RUN)
|
| 132 |
+
eef_extrinsic: "dict[str, object] | None" = None, # side -> (4,4)/path/None
|
| 133 |
+
image_source: str = "auto",
|
| 134 |
+
image_obs_keys: "dict[str, str] | None" = None, # side -> obs.images key
|
| 135 |
+
record_dir: str | None = None,
|
| 136 |
+
):
|
| 137 |
+
self.upsample = max(int(upsample), 1)
|
| 138 |
+
self.chunk_fps = float(chunk_fps)
|
| 139 |
+
self.dt = 1.0 / (self.chunk_fps * self.upsample)
|
| 140 |
+
self.action_horizon = max(0, int(action_horizon))
|
| 141 |
+
self.prompt = prompt
|
| 142 |
+
self.image_source = str(image_source).lower()
|
| 143 |
+
self.image_obs_keys = image_obs_keys or {"left": "left_wrist", "right": "right_wrist"}
|
| 144 |
+
self.record_dir = record_dir
|
| 145 |
+
|
| 146 |
+
from ..codec import umi_decode
|
| 147 |
+
from ..codec.umi_pi05_server import init_server, resolve_eef_extrinsic
|
| 148 |
+
self._dec = umi_decode
|
| 149 |
+
|
| 150 |
+
# E per side (robot hand frame -> data gripper frame G, T_hand = T_G @ E).
|
| 151 |
+
# Applied SYMMETRICALLY here (input x E^-1, output x E); the server decodes with identity.
|
| 152 |
+
self._E = {}
|
| 153 |
+
self._E_inv = {}
|
| 154 |
+
for s in SIDES:
|
| 155 |
+
e = resolve_eef_extrinsic((eef_extrinsic or {}).get(s))
|
| 156 |
+
self._E[s] = e
|
| 157 |
+
self._E_inv[s] = None if e is None else np.linalg.inv(e)
|
| 158 |
+
log.info("E[%s] = %s", s, "identity" if e is None else np.round(e, 4).tolist())
|
| 159 |
+
|
| 160 |
+
# replay videos per side
|
| 161 |
+
self._frames = {}
|
| 162 |
+
for s in SIDES:
|
| 163 |
+
p = (episode_videos or {}).get(s)
|
| 164 |
+
self._frames[s] = _decode_video_frames(Path(p).resolve()) if p else []
|
| 165 |
+
if self._frames[s]:
|
| 166 |
+
log.info("replay video[%s]: %d frames", s, len(self._frames[s]))
|
| 167 |
+
self._cursor = 0
|
| 168 |
+
self._last_live = {s: None for s in SIDES}
|
| 169 |
+
|
| 170 |
+
# open-loop parquet proprio (both sides from dataset state[16])
|
| 171 |
+
self._pq_state = None
|
| 172 |
+
self.input_source = "live"
|
| 173 |
+
if episode_parquet:
|
| 174 |
+
import pandas as pd
|
| 175 |
+
df = pd.read_parquet(Path(episode_parquet).resolve()).sort_values("frame_index")
|
| 176 |
+
self._pq_state = np.stack(df["observation.state"].to_numpy()).astype(np.float32)
|
| 177 |
+
self.input_source = "parquet"
|
| 178 |
+
log.info("open-loop PARQUET proprio: %s rows=%d", episode_parquet, len(self._pq_state))
|
| 179 |
+
|
| 180 |
+
# config's image keys, in the same left/right roles the model was trained with
|
| 181 |
+
srv = init_server(
|
| 182 |
+
checkpoint_dir=checkpoint_dir,
|
| 183 |
+
config=config,
|
| 184 |
+
openpi_root=openpi_root or "",
|
| 185 |
+
device=device,
|
| 186 |
+
num_denoise_steps=num_denoise_steps,
|
| 187 |
+
prompt=prompt,
|
| 188 |
+
upsample=self.upsample,
|
| 189 |
+
eef_extrinsic=None, # E handled symmetrically HERE
|
| 190 |
+
)
|
| 191 |
+
if srv.num_hands != 2:
|
| 192 |
+
raise ValueError(f"config {config} is not dual-hand (num_hands={srv.num_hands})")
|
| 193 |
+
from ..codec.umi_pi05_server import infer_target_eef
|
| 194 |
+
self._infer = infer_target_eef
|
| 195 |
+
# config image keys: order in srv.image_keys is (base, left, right) filtered
|
| 196 |
+
self._model_image_key = {"left": None, "right": None}
|
| 197 |
+
for k in srv.image_keys:
|
| 198 |
+
if "left" in k:
|
| 199 |
+
self._model_image_key["left"] = k
|
| 200 |
+
elif "right" in k:
|
| 201 |
+
self._model_image_key["right"] = k
|
| 202 |
+
if not all(self._model_image_key.values()):
|
| 203 |
+
raise ValueError(f"could not map config image keys {srv.image_keys} to left/right")
|
| 204 |
+
|
| 205 |
+
self._prev = {s: None for s in SIDES} # previous-cycle [pose7, grip] fallback
|
| 206 |
+
self._T0 = {s: None for s in SIDES} # session first frame, used only with QUAT_PERM
|
| 207 |
+
_quat_perm_advice(checkpoint_dir)
|
| 208 |
+
log.info("UmiPi05DualPolicy ready: config=%s ckpt=%s upsample=%d dt=%.4f source=%s quat_perm=%s",
|
| 209 |
+
config, checkpoint_dir, self.upsample, self.dt, self.input_source, QUAT_PERM)
|
| 210 |
+
|
| 211 |
+
# ------------------------------------------------------------------ helpers
|
| 212 |
+
def reset(self) -> None:
|
| 213 |
+
self._cursor = 0
|
| 214 |
+
self._prev = {s: None for s in SIDES}
|
| 215 |
+
self._T0 = {s: None for s in SIDES}
|
| 216 |
+
|
| 217 |
+
# ---- quaternion-order compensation (see VLA_QUAT_PERM in module doc) ----
|
| 218 |
+
def _to_read(self, poses: np.ndarray, T0: np.ndarray) -> np.ndarray:
|
| 219 |
+
"""True (...,7) -> training read space: re-anchor to first frame, then use wxyz as xyzw."""
|
| 220 |
+
mats = np.linalg.inv(T0) @ self._dec.pose_xyzw_to_matrix(np.asarray(poses, np.float32))
|
| 221 |
+
q = self._dec.matrix_to_quat_xyzw(mats[..., :3, :3]) # (x,y,z,w)
|
| 222 |
+
return np.concatenate([mats[..., :3, 3], q[..., [3, 0, 1, 2]]], -1).astype(np.float32)
|
| 223 |
+
|
| 224 |
+
def _from_read(self, poses: np.ndarray, T0: np.ndarray) -> np.ndarray:
|
| 225 |
+
"""Read space (...,7) -> true: invert the permutation, then undo re-anchoring."""
|
| 226 |
+
p = np.asarray(poses, np.float32)
|
| 227 |
+
mats = T0 @ self._dec.pose_xyzw_to_matrix(
|
| 228 |
+
np.concatenate([p[..., :3], p[..., 3:7][..., [1, 2, 3, 0]]], -1))
|
| 229 |
+
q = self._dec.matrix_to_quat_xyzw(mats[..., :3, :3])
|
| 230 |
+
return np.concatenate([mats[..., :3, 3], q], -1).astype(np.float32)
|
| 231 |
+
|
| 232 |
+
def _image(self, obs: Observation, side: str):
|
| 233 |
+
"""live wrist frame if available/allowed, else replay video at the cursor."""
|
| 234 |
+
if self.image_source in ("live", "auto"):
|
| 235 |
+
frame = (obs.images or {}).get(self.image_obs_keys[side])
|
| 236 |
+
if frame is not None and getattr(frame, "data", None):
|
| 237 |
+
buf = np.frombuffer(frame.data, dtype=np.uint8)
|
| 238 |
+
bgr = cv2.imdecode(buf, cv2.IMREAD_COLOR)
|
| 239 |
+
if bgr is not None:
|
| 240 |
+
self._last_live[side] = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 241 |
+
if self._last_live[side] is not None:
|
| 242 |
+
return self._last_live[side], True
|
| 243 |
+
if self.image_source == "live":
|
| 244 |
+
raise RuntimeError(f"image_source=live but no {side} wrist frame yet")
|
| 245 |
+
frames = self._frames[side]
|
| 246 |
+
if not frames:
|
| 247 |
+
raise RuntimeError(f"no replay video for side {side} and no live frame")
|
| 248 |
+
return frames[min(self._cursor, len(frames) - 1)], False
|
| 249 |
+
|
| 250 |
+
def _compose(self, poses: np.ndarray, T: np.ndarray) -> np.ndarray:
|
| 251 |
+
"""(...,7) poses @ T (right-multiply a fixed transform)."""
|
| 252 |
+
mats = self._dec.pose_xyzw_to_matrix(np.asarray(poses, np.float32))
|
| 253 |
+
out = mats @ T
|
| 254 |
+
pos = out[..., :3, 3]
|
| 255 |
+
quat = self._dec.matrix_to_quat_xyzw(out[..., :3, :3])
|
| 256 |
+
return np.concatenate([pos, quat], axis=-1).astype(np.float32)
|
| 257 |
+
|
| 258 |
+
def _proprio(self, obs: Observation, side: str):
|
| 259 |
+
"""[prev, cur] pose (2,7) + gripper (2,), model G-frame, dataset gripper scale."""
|
| 260 |
+
if self._pq_state is not None:
|
| 261 |
+
i = min(self._cursor, len(self._pq_state) - 1)
|
| 262 |
+
p = max(i - 1, 0)
|
| 263 |
+
a, b = POSE_SLICES[side]
|
| 264 |
+
pose = self._pq_state[[p, i], a:b]
|
| 265 |
+
grip = self._pq_state[[p, i], GRIP_INDEX[side]]
|
| 266 |
+
return pose.astype(np.float32), grip.astype(np.float32), "parquet"
|
| 267 |
+
cur = np.asarray((obs.eef or {}).get(side), np.float32)
|
| 268 |
+
if cur is None or cur.shape != (7,):
|
| 269 |
+
raise RuntimeError(f"obs.eef[{side}] missing/bad")
|
| 270 |
+
cur_g = float((obs.gripper or {}).get(side, 0.0))
|
| 271 |
+
prev = (obs.eef_prev or {}).get(side)
|
| 272 |
+
if prev is not None and len(prev) == 7:
|
| 273 |
+
prev, src = np.asarray(prev, np.float32), "client"
|
| 274 |
+
elif self._prev[side] is not None:
|
| 275 |
+
prev, src = self._prev[side][0], "cycle"
|
| 276 |
+
else:
|
| 277 |
+
prev, src = cur.copy(), "cur"
|
| 278 |
+
prev_g = float((obs.gripper_prev or {}).get(side, self._prev[side][1] if self._prev[side] else cur_g))
|
| 279 |
+
pose = np.stack([prev, cur])
|
| 280 |
+
if self._E_inv[side] is not None: # hand frame -> G frame
|
| 281 |
+
pose = self._compose(pose, self._E_inv[side])
|
| 282 |
+
return pose.astype(np.float32), np.asarray([prev_g, cur_g], np.float32), src
|
| 283 |
+
|
| 284 |
+
# ------------------------------------------------------------------ main
|
| 285 |
+
def infer(self, obs: Observation) -> Action:
|
| 286 |
+
imgs, live_flags = {}, {}
|
| 287 |
+
for s in SIDES:
|
| 288 |
+
img, live = self._image(obs, s)
|
| 289 |
+
imgs[self._model_image_key[s]] = img
|
| 290 |
+
live_flags[s] = live
|
| 291 |
+
|
| 292 |
+
pose = np.zeros((2, 2, 7), np.float32) # [prev,cur] x [left,right] x 7
|
| 293 |
+
grip = np.zeros((2, 2), np.float32)
|
| 294 |
+
srcs = {}
|
| 295 |
+
for h, s in enumerate(SIDES):
|
| 296 |
+
p, g, src = self._proprio(obs, s)
|
| 297 |
+
pose[:, h], grip[:, h], srcs[s] = p, g, src
|
| 298 |
+
|
| 299 |
+
# Quaternion-order compensation: convert only the model input to read space.
|
| 300 |
+
# Do not modify pose in place: self._prev stores pose[1,h] as next cycle's prev.
|
| 301 |
+
pose_in = pose
|
| 302 |
+
if QUAT_PERM:
|
| 303 |
+
pose_in = pose.copy()
|
| 304 |
+
for h, s in enumerate(SIDES):
|
| 305 |
+
if self._T0[s] is None: # session first frame = per-episode training origin
|
| 306 |
+
self._T0[s] = self._dec.pose_xyzw_to_matrix(pose[1, h])
|
| 307 |
+
pose_in[:, h] = self._to_read(pose[:, h], self._T0[s])
|
| 308 |
+
|
| 309 |
+
t0 = time.time()
|
| 310 |
+
out = self._infer({"eef_pose": pose_in, "gripper": grip, "images": imgs,
|
| 311 |
+
"prompt": self.prompt, "upsample": self.upsample})
|
| 312 |
+
t_ms = (time.time() - t0) * 1e3
|
| 313 |
+
|
| 314 |
+
tgt = np.asarray(out["target_eef_pose"], np.float32) # (2, M, 7) G-frame
|
| 315 |
+
if QUAT_PERM: # read-space absolute targets -> true
|
| 316 |
+
for h, s in enumerate(SIDES):
|
| 317 |
+
tgt[h] = self._from_read(tgt[h], self._T0[s])
|
| 318 |
+
grp = np.asarray(out["target_gripper"], np.float32) # (2, M)
|
| 319 |
+
exec_frames = int(out.get("horizon", 0)) or max(1, tgt.shape[1] // self.upsample)
|
| 320 |
+
if self.action_horizon > 0 and tgt.shape[1] > 1:
|
| 321 |
+
keep = max(1, min(tgt.shape[1], self.action_horizon * self.upsample))
|
| 322 |
+
tgt, grp = tgt[:, :keep], grp[:, :keep]
|
| 323 |
+
exec_frames = min(exec_frames, self.action_horizon)
|
| 324 |
+
|
| 325 |
+
eef_traj, grip_traj = {}, {}
|
| 326 |
+
for h, s in enumerate(SIDES):
|
| 327 |
+
t = tgt[h]
|
| 328 |
+
if self._E[s] is not None: # G frame -> hand frame
|
| 329 |
+
t = self._compose(t, self._E[s])
|
| 330 |
+
eef_traj[s] = t.tolist()
|
| 331 |
+
grip_traj[s] = [float(g) for g in grp[h]]
|
| 332 |
+
|
| 333 |
+
action = Action(
|
| 334 |
+
seq=obs.seq,
|
| 335 |
+
stamp=time.time(),
|
| 336 |
+
control="eef_pose",
|
| 337 |
+
eef_target={s: eef_traj[s][0] for s in SIDES},
|
| 338 |
+
gripper={s: grip_traj[s][0] for s in SIDES},
|
| 339 |
+
eef_traj=eef_traj,
|
| 340 |
+
gripper_traj=grip_traj,
|
| 341 |
+
dt=self.dt,
|
| 342 |
+
extra={
|
| 343 |
+
"policy": "umi_pi05_dual",
|
| 344 |
+
"n_steps": int(tgt.shape[1]),
|
| 345 |
+
"horizon": int(out.get("horizon", 0)),
|
| 346 |
+
"model_ms": round(t_ms, 1),
|
| 347 |
+
"input_source": self.input_source,
|
| 348 |
+
"prev_src": srcs,
|
| 349 |
+
"image_live": live_flags,
|
| 350 |
+
"cursor": self._cursor,
|
| 351 |
+
},
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# advance per-cycle state
|
| 355 |
+
for h, s in enumerate(SIDES):
|
| 356 |
+
self._prev[s] = (pose[1, h].copy(), float(grip[1, h]))
|
| 357 |
+
self._cursor += exec_frames
|
| 358 |
+
if self.record_dir:
|
| 359 |
+
try:
|
| 360 |
+
rd = Path(self.record_dir)
|
| 361 |
+
rd.mkdir(parents=True, exist_ok=True)
|
| 362 |
+
for s in SIDES:
|
| 363 |
+
img = imgs[self._model_image_key[s]]
|
| 364 |
+
cv2.imwrite(str(rd / f"seq{obs.seq:04d}_{s}.jpg"),
|
| 365 |
+
cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR))
|
| 366 |
+
np.savez_compressed(rd / f"seq{obs.seq:04d}_obs.npz",
|
| 367 |
+
pose_in=pose, grip_in=grip, tgt_G=tgt,
|
| 368 |
+
grip_traj=grp) # (2,M) per-step gripper targets, for visualization
|
| 369 |
+
except Exception as e:
|
| 370 |
+
log.warning("record failed: %s", e)
|
| 371 |
+
log.info("chunk seq=%d steps=%d model=%.0fms src=%s live=%s cursor=%d",
|
| 372 |
+
obs.seq, tgt.shape[1], t_ms, srcs, live_flags, self._cursor)
|
| 373 |
+
return action
|
flexiv-umi-infer/umi_infer/policy_server.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Policy server -- runs on the GPU box.
|
| 2 |
+
|
| 3 |
+
Hosts a Policy behind a websocket. For every Observation it receives it runs
|
| 4 |
+
``policy.infer`` and returns an Action (a trajectory chunk).
|
| 5 |
+
|
| 6 |
+
Run:
|
| 7 |
+
python -m umi_infer.policy_server --policy mock --policy-mode hold
|
| 8 |
+
python -m umi_infer.policy_server --policy pi05 --checkpoint-dir <ckpt> \
|
| 9 |
+
--eef-extrinsic-left data/E_left.npy --eef-extrinsic-right data/E_right.npy
|
| 10 |
+
python -m umi_infer.policy_server --policy flux --flux-export <export> \
|
| 11 |
+
--flux-e-left data/E_left.npy --flux-e-right data/E_right.npy
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import asyncio
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import websockets
|
| 23 |
+
|
| 24 |
+
from .config import MAX_WS_SIZE, Config
|
| 25 |
+
from .policies.base import Policy
|
| 26 |
+
from .policies.mock import MockPolicy
|
| 27 |
+
from .protocol import pack, unpack_observation, wire_log_payload
|
| 28 |
+
|
| 29 |
+
log = logging.getLogger("policy_server")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# One summary line per chunk by default; UMI_WIRE_LOG=1 logs the full action payload.
|
| 33 |
+
WIRE_LOG = bool(int(os.environ.get("UMI_WIRE_LOG", "0")))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _action_brief(a) -> str:
|
| 37 |
+
"""One-line chunk summary: steps / dt / first point and path length per arm / gripper range."""
|
| 38 |
+
tr = getattr(a, "eef_traj", None) or {}
|
| 39 |
+
gt = getattr(a, "gripper_traj", None) or {}
|
| 40 |
+
n = max([len(v) for v in tr.values()] + [0])
|
| 41 |
+
bits = ["%d steps" % n, "dt=%.4f" % float(getattr(a, "dt", 0.0) or 0.0)]
|
| 42 |
+
for s in ("left", "right"):
|
| 43 |
+
v = tr.get(s) or []
|
| 44 |
+
if v:
|
| 45 |
+
d = sum(sum((v[i + 1][k] - v[i][k]) ** 2 for k in range(3)) ** 0.5
|
| 46 |
+
for i in range(len(v) - 1))
|
| 47 |
+
bits.append("%s(%.3f,%.3f,%.3f) path %.0fmm"
|
| 48 |
+
% (s[0].upper(), v[0][0], v[0][1], v[0][2], d * 1000))
|
| 49 |
+
g = gt.get(s) or []
|
| 50 |
+
if g:
|
| 51 |
+
bits.append("%s grip %.1f~%.1f deg" % (s[0].upper(), min(g), max(g)))
|
| 52 |
+
return " ".join(bits)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
async def _handle(ws, policy: Policy, path=None) -> None:
|
| 56 |
+
peer = getattr(ws, "remote_address", "?")
|
| 57 |
+
log.info("client connected: %s", peer)
|
| 58 |
+
policy.reset()
|
| 59 |
+
n = 0
|
| 60 |
+
t_stat = time.time()
|
| 61 |
+
loop = asyncio.get_running_loop()
|
| 62 |
+
try:
|
| 63 |
+
async for msg in ws:
|
| 64 |
+
obs = unpack_observation(msg)
|
| 65 |
+
if WIRE_LOG:
|
| 66 |
+
log.info("recv obs len=%d %s", len(msg), wire_log_payload(obs))
|
| 67 |
+
action = await loop.run_in_executor(None, policy.infer, obs)
|
| 68 |
+
action_bytes = pack(action)
|
| 69 |
+
await ws.send(action_bytes)
|
| 70 |
+
if WIRE_LOG:
|
| 71 |
+
log.info("send action len=%d %s", len(action_bytes),
|
| 72 |
+
wire_log_payload(action))
|
| 73 |
+
else:
|
| 74 |
+
log.info("send seq=%s len=%d %s", action.seq, len(action_bytes),
|
| 75 |
+
_action_brief(action))
|
| 76 |
+
n += 1
|
| 77 |
+
if n % 50 == 0:
|
| 78 |
+
dt = time.time() - t_stat
|
| 79 |
+
t_stat = time.time()
|
| 80 |
+
log.info("served %d (%.1f Hz) last seq=%d imgs=%d",
|
| 81 |
+
n, (50 / dt if dt > 0 else 0.0), obs.seq, len(obs.images))
|
| 82 |
+
except websockets.ConnectionClosed:
|
| 83 |
+
log.info("client disconnected: %s (served %d)", peer, n)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
async def _serve(cfg: Config, policy: Policy) -> None:
|
| 87 |
+
async def handler(ws, path=None):
|
| 88 |
+
await _handle(ws, policy, path)
|
| 89 |
+
|
| 90 |
+
async with websockets.serve(handler, cfg.host, cfg.port, max_size=MAX_WS_SIZE):
|
| 91 |
+
log.info("policy server listening on ws://%s:%d (policy=%s)",
|
| 92 |
+
cfg.host, cfg.port, type(policy).__name__)
|
| 93 |
+
await asyncio.Future() # run forever
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _build_policy(args) -> Policy:
|
| 97 |
+
if args.policy == "flux":
|
| 98 |
+
from .policies.flux_action_dual import FluxActionDualPolicy
|
| 99 |
+
|
| 100 |
+
if not args.flux_export:
|
| 101 |
+
raise SystemExit("--policy flux requires --flux-export (an inference export directory)")
|
| 102 |
+
return FluxActionDualPolicy(
|
| 103 |
+
export_dir=args.flux_export,
|
| 104 |
+
source_dir=args.flux_source,
|
| 105 |
+
resources_dir=args.flux_resources,
|
| 106 |
+
prompt=args.flux_prompt,
|
| 107 |
+
device=args.device,
|
| 108 |
+
extrinsics={"left": args.flux_e_left, "right": args.flux_e_right},
|
| 109 |
+
e_provenance=args.flux_e_provenance,
|
| 110 |
+
image_keys={"left": args.flux_image_left, "right": args.flux_image_right},
|
| 111 |
+
action_horizon=args.flux_horizon,
|
| 112 |
+
sampler=args.flux_sampler,
|
| 113 |
+
steps=args.flux_steps,
|
| 114 |
+
shift=args.flux_shift,
|
| 115 |
+
guidance=args.flux_guidance,
|
| 116 |
+
action_guidance=args.flux_action_guidance,
|
| 117 |
+
seed=args.flux_seed,
|
| 118 |
+
)
|
| 119 |
+
if args.policy == "pi05":
|
| 120 |
+
from .policies.umi_pi05_dual import UmiPi05DualPolicy
|
| 121 |
+
|
| 122 |
+
if not args.checkpoint_dir:
|
| 123 |
+
raise SystemExit("--policy pi05 requires --checkpoint-dir")
|
| 124 |
+
videos = {}
|
| 125 |
+
if args.episode_video_left:
|
| 126 |
+
videos["left"] = args.episode_video_left
|
| 127 |
+
if args.episode_video_right:
|
| 128 |
+
videos["right"] = args.episode_video_right
|
| 129 |
+
return UmiPi05DualPolicy(
|
| 130 |
+
checkpoint_dir=args.checkpoint_dir,
|
| 131 |
+
config=args.config,
|
| 132 |
+
num_denoise_steps=args.num_denoise_steps,
|
| 133 |
+
openpi_root=args.openpi_root,
|
| 134 |
+
device=args.device,
|
| 135 |
+
prompt=args.prompt,
|
| 136 |
+
upsample=args.upsample,
|
| 137 |
+
chunk_fps=args.chunk_fps,
|
| 138 |
+
action_horizon=args.action_horizon,
|
| 139 |
+
episode_videos=videos or None,
|
| 140 |
+
episode_parquet=args.episode_parquet,
|
| 141 |
+
eef_extrinsic={"left": args.eef_extrinsic_left, "right": args.eef_extrinsic_right},
|
| 142 |
+
image_source=args.image_source,
|
| 143 |
+
record_dir=args.record_dir,
|
| 144 |
+
)
|
| 145 |
+
cfg = Config()
|
| 146 |
+
chunk_size = args.chunk_size if args.chunk_size is not None else cfg.chunk_size
|
| 147 |
+
chunk_dt = args.chunk_dt if args.chunk_dt is not None else cfg.chunk_dt
|
| 148 |
+
return MockPolicy(mode=args.policy_mode, chunk_size=chunk_size, chunk_dt=chunk_dt)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main() -> None:
|
| 152 |
+
ap = argparse.ArgumentParser(description="UMI policy server")
|
| 153 |
+
ap.add_argument("--host", default="127.0.0.1")
|
| 154 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 155 |
+
ap.add_argument("--policy", default="mock", choices=["mock", "pi05", "flux"])
|
| 156 |
+
ap.add_argument("--device", default="cuda:0", help="torch device for the model")
|
| 157 |
+
# ---- mock ----
|
| 158 |
+
g = ap.add_argument_group("mock")
|
| 159 |
+
g.add_argument("--policy-mode", default="hold", choices=["hold", "wobble", "zero", "traj"],
|
| 160 |
+
help="mock behavior (hold = echo the observed pose, a safe no-op)")
|
| 161 |
+
g.add_argument("--chunk-size", type=int, default=None, help="steps per trajectory chunk")
|
| 162 |
+
g.add_argument("--chunk-dt", type=float, default=None, help="seconds between chunk steps")
|
| 163 |
+
# ---- pi05 (openpi-umi) ----
|
| 164 |
+
g = ap.add_argument_group("pi05 (openpi-umi)")
|
| 165 |
+
g.add_argument("--checkpoint-dir", default=None, help="trained checkpoint step dir")
|
| 166 |
+
g.add_argument("--config", default="pi05_umi_v3", help="openpi train config name")
|
| 167 |
+
g.add_argument("--num-denoise-steps", type=int, default=10, help="pi05 flow-sampling steps")
|
| 168 |
+
g.add_argument("--openpi-root", default=None,
|
| 169 |
+
help="optional openpi source tree (<root>/src/openpi, <root>/model for the tokenizer); "
|
| 170 |
+
"default = the installed openpi package")
|
| 171 |
+
g.add_argument("--prompt", default="fold the clothes", help="task prompt")
|
| 172 |
+
g.add_argument("--upsample", type=int, default=1, help="spline upsample factor of the decoded chunk")
|
| 173 |
+
g.add_argument("--chunk-fps", type=float, default=30.0, help="native chunk fps (dt = 1/(fps*upsample))")
|
| 174 |
+
g.add_argument("--action-horizon", type=int, default=0,
|
| 175 |
+
help="return only the first N model frames of each chunk (0 = full chunk)")
|
| 176 |
+
g.add_argument("--eef-extrinsic-left", default=None,
|
| 177 |
+
help="LEFT E: .npy 4x4 (data camera frame -> flange, T_flange = T_cam @ E); none = identity")
|
| 178 |
+
g.add_argument("--eef-extrinsic-right", default=None, help="RIGHT E, same format")
|
| 179 |
+
g.add_argument("--image-source", default="live", choices=["live", "replay", "auto"],
|
| 180 |
+
help="live = obs.images; replay = episode videos; auto = live if present else replay")
|
| 181 |
+
g.add_argument("--episode-video-left", default=None, help="LEFT episode mp4 for replay/auto")
|
| 182 |
+
g.add_argument("--episode-video-right", default=None, help="RIGHT episode mp4 for replay/auto")
|
| 183 |
+
g.add_argument("--episode-parquet", default=None,
|
| 184 |
+
help="replay proprio from a dataset episode (fully open loop; output is in the dataset "
|
| 185 |
+
"frame, use with a dry-run client only)")
|
| 186 |
+
g.add_argument("--record-dir", default=None,
|
| 187 |
+
help="write <dir>/<timestamp>/ with meta.json, received images and one JSON line per "
|
| 188 |
+
"inference (joins the client --record CSV on seq)")
|
| 189 |
+
# ---- flux (flux-umi) ----
|
| 190 |
+
g = ap.add_argument_group("flux (flux-umi)")
|
| 191 |
+
g.add_argument("--flux-export", default=None, help="FLUX inference export (config.json + model.safetensors)")
|
| 192 |
+
g.add_argument("--flux-source", default=None,
|
| 193 |
+
help="optional flux_action source dir put on sys.path; default = the installed package")
|
| 194 |
+
g.add_argument("--flux-resources", default=None,
|
| 195 |
+
help="dir with video_vae.safetensors and text_encoder/ (default: $FLUX_RESOURCES)")
|
| 196 |
+
g.add_argument("--flux-prompt", default="fold the clothes")
|
| 197 |
+
g.add_argument("--flux-e-left", default=None, help="LEFT E .npy (required)")
|
| 198 |
+
g.add_argument("--flux-e-right", default=None, help="RIGHT E .npy (required)")
|
| 199 |
+
g.add_argument("--flux-e-provenance", default=None,
|
| 200 |
+
help="E_from_urdf.json written by export_E; checks both E files against it")
|
| 201 |
+
g.add_argument("--flux-image-left", default="left_wrist")
|
| 202 |
+
g.add_argument("--flux-image-right", default="right_wrist")
|
| 203 |
+
g.add_argument("--flux-horizon", type=int, default=0, help="first N frames, 0 = all 32")
|
| 204 |
+
g.add_argument("--flux-sampler", choices=["euler", "cosmos_unipc"], default="euler")
|
| 205 |
+
g.add_argument("--flux-steps", type=int, default=4)
|
| 206 |
+
g.add_argument("--flux-shift", type=float, default=42.0,
|
| 207 |
+
help="sampler shift; matching the training timestep shift worked better than 5.0")
|
| 208 |
+
g.add_argument("--flux-guidance", type=float, default=1.0)
|
| 209 |
+
g.add_argument("--flux-action-guidance", type=float, default=1.0)
|
| 210 |
+
g.add_argument("--flux-seed", type=int, default=0)
|
| 211 |
+
args = ap.parse_args()
|
| 212 |
+
if args.flux_resources is None:
|
| 213 |
+
from .policies.flux_action_dual import DEFAULT_RESOURCES
|
| 214 |
+
args.flux_resources = DEFAULT_RESOURCES
|
| 215 |
+
logging.basicConfig(level=logging.INFO,
|
| 216 |
+
format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
| 217 |
+
cfg = Config(host=args.host, port=args.port)
|
| 218 |
+
policy = _build_policy(args)
|
| 219 |
+
try:
|
| 220 |
+
asyncio.run(_serve(cfg, policy))
|
| 221 |
+
except KeyboardInterrupt:
|
| 222 |
+
log.info("shutting down")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
if __name__ == "__main__":
|
| 226 |
+
main()
|
flexiv-umi-infer/umi_infer/protocol.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Wire protocol between the robot agent and the VLA policy server.
|
| 2 |
+
|
| 3 |
+
Two message types travel over a websocket, serialized with msgpack:
|
| 4 |
+
|
| 5 |
+
Observation robot agent --> policy server
|
| 6 |
+
Action policy server --> robot agent
|
| 7 |
+
|
| 8 |
+
Images are carried as raw bytes; the ``format`` field says how to decode them
|
| 9 |
+
(``jpeg`` / ``h264`` in production, ``raw_rgb`` from the mock). For compressed
|
| 10 |
+
bitstreams the frame dimensions may be unknown at transport time and can be set
|
| 11 |
+
to ``0``. This module is intentionally dependency-light (only msgpack) so it
|
| 12 |
+
imports cleanly on both the robot PC and the GPU box.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from typing import Any, Dict, List
|
| 20 |
+
|
| 21 |
+
import msgpack
|
| 22 |
+
|
| 23 |
+
PROTOCOL_VERSION = 3 # v2: Action.eef_traj/gripper_traj/dt; v3: Observation.eef_prev/gripper_prev
|
| 24 |
+
# (the [prev,cur] motion window -- prev is the same proprio ~pose_dt earlier;
|
| 25 |
+
# all optional, wire back-compat)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class CameraFrame:
|
| 30 |
+
name: str
|
| 31 |
+
format: str # 'jpeg' | 'h264' | 'raw_rgb' | 'mock'
|
| 32 |
+
height: int
|
| 33 |
+
width: int
|
| 34 |
+
data: bytes
|
| 35 |
+
stamp: float = 0.0 # epoch seconds when the frame was captured
|
| 36 |
+
|
| 37 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 38 |
+
return {
|
| 39 |
+
"name": self.name,
|
| 40 |
+
"format": self.format,
|
| 41 |
+
"height": self.height,
|
| 42 |
+
"width": self.width,
|
| 43 |
+
"data": self.data,
|
| 44 |
+
"stamp": self.stamp,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def from_dict(d: Dict[str, Any]) -> "CameraFrame":
|
| 49 |
+
return CameraFrame(
|
| 50 |
+
name=d["name"],
|
| 51 |
+
format=d["format"],
|
| 52 |
+
height=d["height"],
|
| 53 |
+
width=d["width"],
|
| 54 |
+
data=d["data"],
|
| 55 |
+
stamp=d.get("stamp", 0.0),
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class Observation:
|
| 61 |
+
"""One time-step of robot state sent up to the policy."""
|
| 62 |
+
|
| 63 |
+
seq: int
|
| 64 |
+
stamp: float
|
| 65 |
+
images: Dict[str, CameraFrame] = field(default_factory=dict)
|
| 66 |
+
# end-effector cartesian pose in base frame: side -> [x, y, z, qx, qy, qz, qw]
|
| 67 |
+
eef: Dict[str, List[float]] = field(default_factory=dict)
|
| 68 |
+
# joint positions in rad: joint_name -> value
|
| 69 |
+
qpos: Dict[str, float] = field(default_factory=dict)
|
| 70 |
+
# gripper opening; SCALE is defined by the IO/policy PATH (not a fixed unit):
|
| 71 |
+
# flexiv<->umi path = DATASET scale in degrees (0 = closed, 90 = fully open), same scale
|
| 72 |
+
# BOTH directions -- also Action.gripper / Action.gripper_traj;
|
| 73 |
+
# mock path = normalized [0,1] (0=open, 1=closed).
|
| 74 |
+
gripper: Dict[str, float] = field(default_factory=dict)
|
| 75 |
+
# PREVIOUS frame of the motion window (~pose_dt before `eef`/`gripper`): the
|
| 76 |
+
# client samples two real proprio frames a short delta apart so the policy can
|
| 77 |
+
# read motion direction from [prev, cur]. Same shapes/sides as eef/gripper.
|
| 78 |
+
eef_prev: Dict[str, List[float]] = field(default_factory=dict)
|
| 79 |
+
gripper_prev: Dict[str, float] = field(default_factory=dict)
|
| 80 |
+
# actual achieved seconds between prev and cur (target is pose_dt; 0 if no prev)
|
| 81 |
+
pose_dt: float = 0.0
|
| 82 |
+
extra: Dict[str, Any] = field(default_factory=dict)
|
| 83 |
+
|
| 84 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 85 |
+
return {
|
| 86 |
+
"v": PROTOCOL_VERSION,
|
| 87 |
+
"type": "obs",
|
| 88 |
+
"seq": self.seq,
|
| 89 |
+
"stamp": self.stamp,
|
| 90 |
+
"images": {k: v.to_dict() for k, v in self.images.items()},
|
| 91 |
+
"eef": self.eef,
|
| 92 |
+
"qpos": self.qpos,
|
| 93 |
+
"gripper": self.gripper,
|
| 94 |
+
"eef_prev": self.eef_prev,
|
| 95 |
+
"gripper_prev": self.gripper_prev,
|
| 96 |
+
"pose_dt": self.pose_dt,
|
| 97 |
+
"extra": self.extra,
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def from_dict(d: Dict[str, Any]) -> "Observation":
|
| 102 |
+
return Observation(
|
| 103 |
+
seq=d["seq"],
|
| 104 |
+
stamp=d["stamp"],
|
| 105 |
+
images={k: CameraFrame.from_dict(v) for k, v in d.get("images", {}).items()},
|
| 106 |
+
eef=d.get("eef", {}),
|
| 107 |
+
qpos=d.get("qpos", {}),
|
| 108 |
+
gripper=d.get("gripper", {}),
|
| 109 |
+
eef_prev=d.get("eef_prev", {}),
|
| 110 |
+
gripper_prev=d.get("gripper_prev", {}),
|
| 111 |
+
pose_dt=d.get("pose_dt", 0.0),
|
| 112 |
+
extra=d.get("extra", {}),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@dataclass
|
| 117 |
+
class Action:
|
| 118 |
+
"""One control command returned by the policy.
|
| 119 |
+
|
| 120 |
+
The policy may return either a single target (``eef_target``/``gripper``) or a
|
| 121 |
+
short *trajectory chunk* (``eef_traj``/``gripper_traj`` + ``dt``) of K future
|
| 122 |
+
steps that the robot executes locally at a fixed rate. ``eef_target``/``gripper``
|
| 123 |
+
stay as a length-1 fallback so single-pose policies keep working unchanged.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
seq: int # echoes the Observation.seq this action responds to
|
| 127 |
+
stamp: float
|
| 128 |
+
control: str = "eef_pose" # 'eef_pose' | 'joint'
|
| 129 |
+
# cartesian targets in base frame: side -> [x, y, z, qx, qy, qz, qw]
|
| 130 |
+
eef_target: Dict[str, List[float]] = field(default_factory=dict)
|
| 131 |
+
# gripper command; SCALE is defined by the IO/policy PATH, same as Observation.gripper
|
| 132 |
+
# (flexiv<->umi = DATASET scale in degrees; mock = normalized [0,1]): side -> value
|
| 133 |
+
gripper: Dict[str, float] = field(default_factory=dict)
|
| 134 |
+
# joint targets in rad (used when control == 'joint'): joint_name -> value
|
| 135 |
+
joint_target: Dict[str, float] = field(default_factory=dict)
|
| 136 |
+
# trajectory chunk: side -> [ [x,y,z,qx,qy,qz,qw], ... K steps ]
|
| 137 |
+
eef_traj: Dict[str, List[List[float]]] = field(default_factory=dict)
|
| 138 |
+
# per-step gripper aligned with eef_traj: side -> [ g0, g1, ... ]
|
| 139 |
+
gripper_traj: Dict[str, List[float]] = field(default_factory=dict)
|
| 140 |
+
# seconds between consecutive trajectory steps (0 => single-step fallback)
|
| 141 |
+
dt: float = 0.0
|
| 142 |
+
extra: Dict[str, Any] = field(default_factory=dict)
|
| 143 |
+
|
| 144 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 145 |
+
return {
|
| 146 |
+
"v": PROTOCOL_VERSION,
|
| 147 |
+
"type": "action",
|
| 148 |
+
"seq": self.seq,
|
| 149 |
+
"stamp": self.stamp,
|
| 150 |
+
"control": self.control,
|
| 151 |
+
"eef_target": self.eef_target,
|
| 152 |
+
"gripper": self.gripper,
|
| 153 |
+
"joint_target": self.joint_target,
|
| 154 |
+
"eef_traj": self.eef_traj,
|
| 155 |
+
"gripper_traj": self.gripper_traj,
|
| 156 |
+
"dt": self.dt,
|
| 157 |
+
"extra": self.extra,
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
@staticmethod
|
| 161 |
+
def from_dict(d: Dict[str, Any]) -> "Action":
|
| 162 |
+
return Action(
|
| 163 |
+
seq=d["seq"],
|
| 164 |
+
stamp=d["stamp"],
|
| 165 |
+
control=d.get("control", "eef_pose"),
|
| 166 |
+
eef_target=d.get("eef_target", {}),
|
| 167 |
+
gripper=d.get("gripper", {}),
|
| 168 |
+
joint_target=d.get("joint_target", {}),
|
| 169 |
+
eef_traj=d.get("eef_traj", {}),
|
| 170 |
+
gripper_traj=d.get("gripper_traj", {}),
|
| 171 |
+
dt=d.get("dt", 0.0),
|
| 172 |
+
extra=d.get("extra", {}),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
def as_steps(self) -> "tuple[List[Dict[str, Any]], float]":
|
| 176 |
+
"""Normalize to ``(steps, dt)`` for the robot-side executor.
|
| 177 |
+
|
| 178 |
+
Each step is ``{"eef": {side: [7]}, "gripper": {side: float}}``. When a
|
| 179 |
+
trajectory is present it is expanded step-by-step (sides/gripper of unequal
|
| 180 |
+
length are clamped to their last value); otherwise a single step is built
|
| 181 |
+
from ``eef_target``/``gripper`` with ``dt = 0``.
|
| 182 |
+
"""
|
| 183 |
+
if self.eef_traj:
|
| 184 |
+
sides = [s for s, seq in self.eef_traj.items() if seq]
|
| 185 |
+
k = max((len(self.eef_traj[s]) for s in sides), default=0)
|
| 186 |
+
steps: List[Dict[str, Any]] = []
|
| 187 |
+
for i in range(k):
|
| 188 |
+
eef = {s: self.eef_traj[s][i if i < len(self.eef_traj[s]) else -1] for s in sides}
|
| 189 |
+
grip = {
|
| 190 |
+
s: float(g[i if i < len(g) else -1])
|
| 191 |
+
for s, g in self.gripper_traj.items() if g
|
| 192 |
+
}
|
| 193 |
+
steps.append({"eef": eef, "gripper": grip})
|
| 194 |
+
return steps, float(self.dt)
|
| 195 |
+
return [{"eef": dict(self.eef_target), "gripper": dict(self.gripper)}], 0.0
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def pack(obj: "Observation | Action") -> bytes:
|
| 199 |
+
"""Serialize an Observation or Action to msgpack bytes."""
|
| 200 |
+
return msgpack.packb(obj.to_dict(), use_bin_type=True)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def unpack_observation(b: bytes) -> Observation:
|
| 204 |
+
return Observation.from_dict(msgpack.unpackb(b, raw=False))
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def unpack_action(b: bytes) -> Action:
|
| 208 |
+
return Action.from_dict(msgpack.unpackb(b, raw=False))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _sanitize_for_wire_log(value: Any) -> Any:
|
| 212 |
+
if isinstance(value, bytes):
|
| 213 |
+
return {
|
| 214 |
+
"bytes": len(value),
|
| 215 |
+
"prefix_hex": value[:8].hex(),
|
| 216 |
+
}
|
| 217 |
+
if isinstance(value, dict):
|
| 218 |
+
return {k: _sanitize_for_wire_log(v) for k, v in value.items()}
|
| 219 |
+
if isinstance(value, list):
|
| 220 |
+
return [_sanitize_for_wire_log(v) for v in value]
|
| 221 |
+
if isinstance(value, tuple):
|
| 222 |
+
return [_sanitize_for_wire_log(v) for v in value]
|
| 223 |
+
return value
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def wire_log_payload(obj: Observation | Action) -> str:
|
| 227 |
+
"""Return a compact JSON string for wire-level logging."""
|
| 228 |
+
return json.dumps(_sanitize_for_wire_log(obj.to_dict()), ensure_ascii=False, sort_keys=True)
|
flexiv-umi-infer/umi_infer/robot_agent.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot agent -- runs on the robot PC.
|
| 2 |
+
|
| 3 |
+
Drives the control loop: grab an Observation from RobotIO, send it to the policy
|
| 4 |
+
server, receive an Action, apply it. The servo loop runs locally on the robot;
|
| 5 |
+
policy inference is paced separately. Reconnects if the server drops.
|
| 6 |
+
|
| 7 |
+
Run:
|
| 8 |
+
python -m umi_infer.robot_agent --io mock # no hardware
|
| 9 |
+
python -m umi_infer.robot_agent --io flexiv --live-camera # dry run (no motion)
|
| 10 |
+
python -m umi_infer.robot_agent --io flexiv --live-camera --live --gripper # moves!
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import asyncio
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
import websockets
|
| 22 |
+
|
| 23 |
+
from .config import MAX_WS_SIZE, Config
|
| 24 |
+
from .protocol import pack, unpack_action, wire_log_payload
|
| 25 |
+
from .robot_io.base import RobotIO
|
| 26 |
+
|
| 27 |
+
log = logging.getLogger("robot_agent")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
async def _run_session(uri: str, io: RobotIO, cfg: Config) -> None:
|
| 31 |
+
"""Pace inference by the local executor's buffer, not a fixed network loop.
|
| 32 |
+
|
| 33 |
+
The robot-side executor (RobotIO) runs the trajectory chunk at a fixed local
|
| 34 |
+
rate. This loop only decides *when* to ask the policy for the next chunk:
|
| 35 |
+
- sync : wait until the whole chunk is consumed (frac=1.0, + settle), then
|
| 36 |
+
grab a FRESH observation -> the VLA always plans from current state.
|
| 37 |
+
- async: refill at ``refill_at_fraction`` and overlap inference with the tail.
|
| 38 |
+
``control_rate_hz`` is a cap on request cadence (matters only for degenerate
|
| 39 |
+
single-step chunks, where ``needs_refill`` is always True).
|
| 40 |
+
"""
|
| 41 |
+
frac = 1.0 if cfg.inference_mode == "sync" else cfg.refill_at_fraction
|
| 42 |
+
min_interval = 1.0 / cfg.control_rate_hz if cfg.control_rate_hz > 0 else 0.0
|
| 43 |
+
async with websockets.connect(uri, max_size=MAX_WS_SIZE, proxy=None) as ws:
|
| 44 |
+
log.info("connected to %s (inference_mode=%s frac=%.2f)", uri, cfg.inference_mode, frac)
|
| 45 |
+
n = 0
|
| 46 |
+
t_stat = time.time()
|
| 47 |
+
while True:
|
| 48 |
+
# trigger: wait until the local executor needs the next chunk
|
| 49 |
+
while not io.needs_refill(frac):
|
| 50 |
+
await asyncio.sleep(0.005)
|
| 51 |
+
|
| 52 |
+
t0 = time.perf_counter()
|
| 53 |
+
obs = io.get_observation()
|
| 54 |
+
obs_bytes = pack(obs)
|
| 55 |
+
log.debug("send obs len=%d %s", len(obs_bytes), wire_log_payload(obs))
|
| 56 |
+
await ws.send(obs_bytes)
|
| 57 |
+
action_bytes = await ws.recv()
|
| 58 |
+
action = unpack_action(action_bytes)
|
| 59 |
+
log.debug("recv action len=%d %s", len(action_bytes), wire_log_payload(action))
|
| 60 |
+
rtt_ms = (time.perf_counter() - t0) * 1e3
|
| 61 |
+
io.apply_action(action)
|
| 62 |
+
|
| 63 |
+
n += 1
|
| 64 |
+
if n % 50 == 0:
|
| 65 |
+
dt = time.time() - t_stat
|
| 66 |
+
t_stat = time.time()
|
| 67 |
+
log.info("cycle %d rate=%.1fHz rtt=%.1fms action.seq=%d ctrl=%s",
|
| 68 |
+
n, (50 / dt if dt > 0 else 0.0), rtt_ms, action.seq, action.control)
|
| 69 |
+
|
| 70 |
+
# rate cap: never request faster than control_rate_hz
|
| 71 |
+
elapsed = time.perf_counter() - t0
|
| 72 |
+
if min_interval > elapsed:
|
| 73 |
+
await asyncio.sleep(min_interval - elapsed)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
async def _main(uri: str, io: RobotIO, cfg: Config) -> None:
|
| 77 |
+
io.start() # the Flexiv IO moves both arms to the start posture here
|
| 78 |
+
try:
|
| 79 |
+
while True:
|
| 80 |
+
try:
|
| 81 |
+
await _run_session(uri, io, cfg)
|
| 82 |
+
except (OSError, websockets.WebSocketException) as e:
|
| 83 |
+
log.warning("connection error: %s", e)
|
| 84 |
+
if not cfg.reconnect:
|
| 85 |
+
break
|
| 86 |
+
log.info("reconnecting in 1s ...")
|
| 87 |
+
await asyncio.sleep(1.0)
|
| 88 |
+
finally:
|
| 89 |
+
io.stop()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _make_io(kind: str, cfg: Config, dry_run: bool = False, pose_dt: float = 0.033, record_path=None,
|
| 93 |
+
live_camera: bool = False, flexiv_kw: dict | None = None,
|
| 94 |
+
mock_images: dict | None = None) -> RobotIO:
|
| 95 |
+
if kind == "flexiv":
|
| 96 |
+
from .robot_io.flexiv import FlexivRobotIO
|
| 97 |
+
return FlexivRobotIO(dry_run=dry_run, servo_rate_hz=cfg.servo_rate_hz,
|
| 98 |
+
pose_dt=pose_dt, record_path=record_path,
|
| 99 |
+
live_camera=live_camera,
|
| 100 |
+
**(flexiv_kw or {}))
|
| 101 |
+
if kind == "mock":
|
| 102 |
+
from .robot_io.mock import MockRobotIO
|
| 103 |
+
return MockRobotIO(cameras=cfg.cameras, image_files=mock_images)
|
| 104 |
+
raise ValueError(f"unknown io kind: {kind}")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main() -> None:
|
| 108 |
+
ap = argparse.ArgumentParser(description="UMI robot agent")
|
| 109 |
+
ap.add_argument("--server", default="ws://127.0.0.1:8765", help="policy server ws:// URI")
|
| 110 |
+
ap.add_argument("--rate", type=float, default=2.0, help="cap on inference-request Hz")
|
| 111 |
+
ap.add_argument("--servo-rate", type=float, default=100.0, help="robot-side servo Hz")
|
| 112 |
+
ap.add_argument("--inference-mode", default="sync", choices=["sync", "async"],
|
| 113 |
+
help="sync: run the whole chunk then re-infer from fresh state; "
|
| 114 |
+
"async: refill early and overlap inference with the chunk tail")
|
| 115 |
+
ap.add_argument("--refill-fraction", type=float, default=0.7,
|
| 116 |
+
help="async only: request the next chunk at this consumed fraction")
|
| 117 |
+
ap.add_argument("--io", default="mock", choices=["mock", "flexiv"])
|
| 118 |
+
ap.add_argument("--no-reconnect", action="store_true")
|
| 119 |
+
ap.add_argument("--pose-dt", type=float, default=0.033,
|
| 120 |
+
help="target delta (s) between the two proprio frames [prev, cur] sent to the "
|
| 121 |
+
"policy (0.033 = one frame at 30 fps)")
|
| 122 |
+
ap.add_argument("--record", default=None,
|
| 123 |
+
help="CSV of commanded vs measured EEF/gripper per servo tick "
|
| 124 |
+
"(+ <name>.chunks.jsonl with per-chunk model output and prechecks)")
|
| 125 |
+
ap.add_argument("--live-camera", action="store_true",
|
| 126 |
+
help="stream both wrist cameras into obs.images (needed for real inference)")
|
| 127 |
+
ap.add_argument("--mock-image-left", default=None, help="--io mock: JPEG sent as the left wrist image")
|
| 128 |
+
ap.add_argument("--mock-image-right", default=None, help="--io mock: JPEG sent as the right wrist image")
|
| 129 |
+
g = ap.add_argument_group("Flexiv dual arm (--io flexiv)")
|
| 130 |
+
g.add_argument("--left-sn", default=None, help="left arm serial (default $FLEXIV_LEFT_SN)")
|
| 131 |
+
g.add_argument("--right-sn", default=None, help="right arm serial (default $FLEXIV_RIGHT_SN)")
|
| 132 |
+
g.add_argument("--urdf", default=None, help="combined dual-arm URDF (default $FLEXIV_URDF)")
|
| 133 |
+
g.add_argument("--live", action="store_true",
|
| 134 |
+
help="actually move the arms. Without it the agent is a DRY RUN "
|
| 135 |
+
"(full pipeline, no motion commands)")
|
| 136 |
+
g.add_argument("--gripper", action="store_true", help="drive both grippers from the model's gripper channel")
|
| 137 |
+
g.add_argument("--play-scale", type=float, default=None,
|
| 138 |
+
help="stretch each step on the wall clock by this factor (default 2.5). Does not change dt, "
|
| 139 |
+
"so the motion seen in the state is unaffected. At 1x about 30%% of model points "
|
| 140 |
+
"exceed max_linear_acc=2.0 and get clipped by the controller; slowing by k cuts "
|
| 141 |
+
"acceleration by k^2")
|
| 142 |
+
g.add_argument("--nullspace-weight", type=float, default=0.5,
|
| 143 |
+
help="weight pulling the elbow (null space) to the start posture [0.1, 1.0]: "
|
| 144 |
+
"0.1 soft / 0.5 default / 1.0 stiff")
|
| 145 |
+
g.add_argument("--first-steps", type=int, default=0,
|
| 146 |
+
help="execute only the first N steps of the first chunk (0 = all)")
|
| 147 |
+
g.add_argument("--steps", type=int, default=0,
|
| 148 |
+
help="execute only the first N steps of every later chunk (0 = all)")
|
| 149 |
+
g.add_argument("--reach-scale-right", type=float, default=None,
|
| 150 |
+
help="scale right-arm displacement within a chunk (1.0 = off); origin = measured "
|
| 151 |
+
"position at observation time, orientation unchanged")
|
| 152 |
+
g.add_argument("--grip-offset-deg", type=float, default=None,
|
| 153 |
+
help="subtract this from every model gripper opening before executing (default 3.0; "
|
| 154 |
+
"0 = pass through). Lets a grasp saturate the lead clamp so force is kp*lead")
|
| 155 |
+
g.add_argument("--anchor-deg", type=float, nargs=7, default=None,
|
| 156 |
+
help="start posture for both arms [deg] (default: data/anchor.json)")
|
| 157 |
+
g.add_argument("--anchor-deg-left", type=float, nargs=7, default=None)
|
| 158 |
+
g.add_argument("--anchor-deg-right", type=float, nargs=7, default=None)
|
| 159 |
+
g.add_argument("--monitor-min-dist", type=float, default=0.02,
|
| 160 |
+
help="Flexiv SelfCollisionMonitor threshold [m], link to link. It does NOT see the "
|
| 161 |
+
"gripper, which reaches ~16 cm past the flange")
|
| 162 |
+
g.add_argument("--min-dist", type=float, default=0.02,
|
| 163 |
+
help="per-cycle measured TCP-to-TCP minimum distance [m]")
|
| 164 |
+
g.add_argument("--tool-min-dist", type=float, default=0.02,
|
| 165 |
+
help="arm-to-arm distance including gripper geometry [m]; the only check that sees the grippers")
|
| 166 |
+
g.add_argument("--max-step-mm", type=float, default=60.0, help="max jump between adjacent chunk steps [mm]")
|
| 167 |
+
g.add_argument("--ik-check", default="truncate", choices=["off", "warn", "truncate", "abort"],
|
| 168 |
+
help="what to do when the vendor reachability precheck fails")
|
| 169 |
+
g.add_argument("--no-monitor", action="store_true", help="disable the self-collision monitor (not recommended)")
|
| 170 |
+
g.add_argument("--no-feedforward", action="store_true", help="do not send feed-forward velocity")
|
| 171 |
+
g.add_argument("--kx-ratio", type=float, default=0.6, help="Cartesian stiffness = ratio x K_x_nom")
|
| 172 |
+
g.add_argument("--zx", type=float, default=0.7, help="Cartesian damping ratio [0.3, 0.8]")
|
| 173 |
+
g.add_argument("--cam-format", default="jpeg", choices=["jpeg", "yuv420p"],
|
| 174 |
+
help="wrist image transport: jpeg (pi05) / yuv420p raw planes (FLUX, converted on the "
|
| 175 |
+
"policy side with the same pyav call as training)")
|
| 176 |
+
g.add_argument("--cam-kbps", type=int, default=512, help="camera live-stream bitrate, kbps (dual-fisheye frame)")
|
| 177 |
+
g.add_argument("--rollout-root", default=os.environ.get("FLEXIV_ROLLOUT_ROOT", "rollouts"),
|
| 178 |
+
help="per-frame rollout recording root; one subdirectory per run (robot_io/rollout_rec.py)")
|
| 179 |
+
g.add_argument("--no-rollout", action="store_true", help="do not record the rollout")
|
| 180 |
+
g.add_argument("--rollout-cam-hz", type=float, default=10.0,
|
| 181 |
+
help="rate of live wrist frames in the rollout; 0 = only the frames sent to the model")
|
| 182 |
+
args = ap.parse_args()
|
| 183 |
+
for _n in ("websockets", "websockets.client", "websockets.server", "can"):
|
| 184 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 185 |
+
logging.basicConfig(level=logging.INFO,
|
| 186 |
+
format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
| 187 |
+
dry_run = args.io == "flexiv" and not args.live
|
| 188 |
+
if dry_run:
|
| 189 |
+
log.warning("DRY-RUN: robot will NOT move (no motion commands)")
|
| 190 |
+
elif args.io == "flexiv":
|
| 191 |
+
log.warning("LIVE: the robot WILL move. Keep a hand on the e-stop!")
|
| 192 |
+
cfg = Config(control_rate_hz=args.rate, servo_rate_hz=args.servo_rate,
|
| 193 |
+
reconnect=not args.no_reconnect, inference_mode=args.inference_mode,
|
| 194 |
+
refill_at_fraction=args.refill_fraction)
|
| 195 |
+
flexiv_kw = None
|
| 196 |
+
if args.io == "flexiv":
|
| 197 |
+
anchor = None
|
| 198 |
+
if args.anchor_deg or args.anchor_deg_left or args.anchor_deg_right:
|
| 199 |
+
base = args.anchor_deg or args.anchor_deg_left or args.anchor_deg_right
|
| 200 |
+
anchor = {"left": args.anchor_deg_left or args.anchor_deg or base,
|
| 201 |
+
"right": args.anchor_deg_right or args.anchor_deg or base}
|
| 202 |
+
if args.grip_offset_deg is not None:
|
| 203 |
+
os.environ["FLEXIV_GRIP_OFFSET_DEG"] = "%.3f" % args.grip_offset_deg
|
| 204 |
+
if args.reach_scale_right is not None:
|
| 205 |
+
os.environ["FLEXIV_REACH_SCALE_RIGHT"] = "%.3f" % args.reach_scale_right
|
| 206 |
+
flexiv_kw = dict(
|
| 207 |
+
cam_format=args.cam_format, cam_kbps=args.cam_kbps,
|
| 208 |
+
gripper=args.gripper, anchor_deg=anchor,
|
| 209 |
+
monitor_min_dist=args.monitor_min_dist,
|
| 210 |
+
min_dist=args.min_dist, tool_min_dist=args.tool_min_dist,
|
| 211 |
+
max_step_mm=args.max_step_mm, ik_check=args.ik_check,
|
| 212 |
+
no_monitor=args.no_monitor, feedforward=not args.no_feedforward,
|
| 213 |
+
kx_ratio=args.kx_ratio, zx=args.zx,
|
| 214 |
+
first_steps=args.first_steps, steps=args.steps,
|
| 215 |
+
nullspace_weight=args.nullspace_weight,
|
| 216 |
+
rollout_root=None if args.no_rollout else args.rollout_root,
|
| 217 |
+
rollout_cam_hz=args.rollout_cam_hz)
|
| 218 |
+
for k, v in (("left_sn", args.left_sn), ("right_sn", args.right_sn), ("urdf", args.urdf),
|
| 219 |
+
("play_scale", args.play_scale)):
|
| 220 |
+
if v is not None:
|
| 221 |
+
flexiv_kw[k] = v
|
| 222 |
+
io = _make_io(args.io, cfg, dry_run=dry_run, pose_dt=args.pose_dt, record_path=args.record,
|
| 223 |
+
live_camera=args.live_camera, flexiv_kw=flexiv_kw,
|
| 224 |
+
mock_images={"left_wrist": args.mock_image_left, "right_wrist": args.mock_image_right})
|
| 225 |
+
try:
|
| 226 |
+
asyncio.run(_main(args.server, io, cfg))
|
| 227 |
+
except KeyboardInterrupt:
|
| 228 |
+
log.info("stopped")
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
main()
|
flexiv-umi-infer/umi_infer/robot_io/__init__.py
ADDED
|
File without changes
|
flexiv-umi-infer/umi_infer/robot_io/base.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RobotIO interface. Hardware integrations (robot_io/flexiv.py) implement it."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from abc import ABC, abstractmethod
|
| 6 |
+
|
| 7 |
+
from ..protocol import Action, Observation
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RobotIO(ABC):
|
| 11 |
+
"""Abstraction over the physical robot, used by the robot agent.
|
| 12 |
+
|
| 13 |
+
All methods run ON the robot PC. ``MockRobotIO`` needs no hardware;
|
| 14 |
+
``FlexivRobotIO`` drives the dual-arm cell. Methods are synchronous
|
| 15 |
+
and should be quick; the agent calls them once per control cycle.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def start(self) -> None:
|
| 20 |
+
"""Initialize hardware / SDK connection."""
|
| 21 |
+
|
| 22 |
+
@abstractmethod
|
| 23 |
+
def get_observation(self) -> Observation:
|
| 24 |
+
"""Grab the latest cameras + EEF pose + joint/gripper state."""
|
| 25 |
+
|
| 26 |
+
@abstractmethod
|
| 27 |
+
def apply_action(self, action: Action) -> None:
|
| 28 |
+
"""Hand a returned Action (a trajectory chunk) to the local executor."""
|
| 29 |
+
|
| 30 |
+
def needs_refill(self, fraction: float) -> bool:
|
| 31 |
+
"""Whether the local executor's buffer is consumed past ``fraction`` and a
|
| 32 |
+
new chunk should be requested. Default: always ready (no local buffering),
|
| 33 |
+
which makes the agent request as fast as its rate cap allows."""
|
| 34 |
+
return True
|
| 35 |
+
|
| 36 |
+
def stop(self) -> None:
|
| 37 |
+
"""Release resources (optional)."""
|
flexiv-umi-infer/umi_infer/robot_io/cam_ids.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Wrist camera identity. Kept free of relative imports so standalone tools can import it too.
|
| 3 |
+
|
| 4 |
+
Each arm's camera serial and fisheye half must be the ones its extrinsic E was calibrated with.
|
| 5 |
+
Pairing E from one camera with images from another raises no error; the policy just moves wrongly.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
SIDES = ("left", "right")
|
| 11 |
+
|
| 12 |
+
# Camera body serial per arm (printed by `insta360_cli_dual discover`).
|
| 13 |
+
CAM_SERIAL = {"left": os.environ.get("INSTA360_LEFT_SN", ""),
|
| 14 |
+
"right": os.environ.get("INSTA360_RIGHT_SN", "")}
|
| 15 |
+
|
| 16 |
+
# Which 960x960 half of the 1920x960 dual-fisheye frame to use ("left" or "right").
|
| 17 |
+
# Pick the lens that faces the workspace.
|
| 18 |
+
CAM_HALF = {"left": os.environ.get("INSTA360_LEFT_HALF", "right"),
|
| 19 |
+
"right": os.environ.get("INSTA360_RIGHT_HALF", "right")}
|
| 20 |
+
|
| 21 |
+
# Observation keys the policy side expects.
|
| 22 |
+
CAM_OBS_KEY = {"left": "left_wrist", "right": "right_wrist"}
|
| 23 |
+
|
| 24 |
+
# Output size. 960 = native half, no resize: training images are raw 960x960 fisheye and the
|
| 25 |
+
# policy resizes to its input size, the same preprocessing chain as in training.
|
| 26 |
+
CAM_OUT_SIZE = int(os.environ.get("FLEXIV_CAM_SIZE", "960"))
|
| 27 |
+
|
| 28 |
+
# Optional hand-eye capture records ({left,right}/poses.json) that check_cam.py cross-checks against.
|
| 29 |
+
HANDEYE_RUNS = os.environ.get("FLEXIV_HANDEYE_RUNS", "")
|
flexiv-umi-infer/umi_infer/robot_io/flexiv.py
ADDED
|
@@ -0,0 +1,1567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RobotIO for a Flexiv Rizon4/Rizon4R dual-arm cell with UMI grippers (robot side of the bridge).
|
| 2 |
+
|
| 3 |
+
IK is not solved here. Flexiv has an onboard Cartesian controller: in
|
| 4 |
+
NRT_CARTESIAN_MOTION_FORCE we send world-frame TCP poses and the controller does IK,
|
| 5 |
+
null-space posture control and impedance tracking. There is no PyBullet on this path;
|
| 6 |
+
`flexivrdk.Model.reachable` is only used as a pre-send reachability check (reject/truncate).
|
| 7 |
+
|
| 8 |
+
Pipeline (paired with policies/umi_pi05_dual.py):
|
| 9 |
+
|
| 10 |
+
get_observation : TCP poses cached by the servo thread (shared world frame) -> protocol (xyzw)
|
| 11 |
+
+ [prev, cur] motion window (from the servo thread's continuous pose history)
|
| 12 |
+
+ measured gripper opening (dataset scale) + two wrist cameras
|
| 13 |
+
apply_action : the policy sends flange pose targets (E already applied on the policy side)
|
| 14 |
+
-> pre-checks (finite / jump / reachability / tool-aware arm distance)
|
| 15 |
+
-> pose trajectory buffer -> servo thread interpolates at servo_rate
|
| 16 |
+
|
| 17 |
+
Frames (all verified on hardware):
|
| 18 |
+
* Reported and commanded poses are both shared-world TCP poses, i.e. the same frame as
|
| 19 |
+
`RobotPair.states().tcp_pose` and `SendCartesianMotionForce` (difference is 0 at rest).
|
| 20 |
+
* Robot TCP == URDF flange (measured offset 0.022 mm / 0.011 deg).
|
| 21 |
+
* Policy-side E = inv(T_flange_cam), exported from the URDF by umi_infer/export_E.py (hand-eye
|
| 22 |
+
calibration is baked into the URDF). So T_G = obs.eef @ E^-1 = T_world_cam = dataset frame.
|
| 23 |
+
Do not add any extra hand-tuned rotation on top of it.
|
| 24 |
+
* Quaternions: Flexiv is wxyz, the protocol is xyzw. Convert only in `_w2x`/`_x2w`.
|
| 25 |
+
|
| 26 |
+
Camera identity: serials come from env vars via cam_ids.py.
|
| 27 |
+
|
| 28 |
+
Safety (all on by default; disabling must be explicit):
|
| 29 |
+
* `SelfCollisionMonitor` at 100 Hz, default 5 cm, stops both arms below threshold.
|
| 30 |
+
WARNING: its collision model only has arm links, not the UMI grippers, so there is an
|
| 31 |
+
extra tool-aware pre-check (pose_math.pair_distance_tools).
|
| 32 |
+
* Per-cycle guard: fault / control mode changed / measured arm distance.
|
| 33 |
+
* `dry_run=True` is the default: everything runs (pre-checks, interpolation) but no motion
|
| 34 |
+
command is sent.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
import csv
|
| 40 |
+
import json
|
| 41 |
+
import logging
|
| 42 |
+
import os
|
| 43 |
+
import sys
|
| 44 |
+
import threading
|
| 45 |
+
import time
|
| 46 |
+
from dataclasses import dataclass, field
|
| 47 |
+
from typing import Dict, List, Optional
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
|
| 51 |
+
from ..protocol import Action, CameraFrame, Observation
|
| 52 |
+
from .base import RobotIO
|
| 53 |
+
|
| 54 |
+
log = logging.getLogger("umi_infer.flexiv")
|
| 55 |
+
|
| 56 |
+
SIDES = ("left", "right")
|
| 57 |
+
IDX = {"left": 0, "right": 1} # all DRDK APIs take (left, right) in this order
|
| 58 |
+
ARM_DOF = 7
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ---- Camera identity --------------------------------------------------------------
|
| 62 |
+
# Constants live in cam_ids.py (no relative imports there; check_cam.py uses it too).
|
| 63 |
+
from .cam_ids import CAM_HALF, CAM_OBS_KEY, CAM_OUT_SIZE, CAM_SERIAL # noqa: E402
|
| 64 |
+
from .kin_flexiv import DATA_DIR, SN as DEFAULT_SN, URDF as DEFAULT_URDF # noqa: E402
|
| 65 |
+
|
| 66 |
+
# ---- Start posture (anchor) ---------------------------------------------------------
|
| 67 |
+
# The start posture decides what the model sees first, and policies are sensitive to it.
|
| 68 |
+
# No built-in fallback: it comes from data/anchor.json (in this tree) or the CLI flags.
|
| 69 |
+
ANCHOR_FILE = os.environ.get("FLEXIV_ANCHOR_FILE", os.path.join(DATA_DIR, "anchor.json"))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def load_anchor():
|
| 73 |
+
"""Read data/anchor.json -> ({side: 7 joint deg}, {side: gripper opening}); (None, zeros) if unreadable."""
|
| 74 |
+
try:
|
| 75 |
+
with open(ANCHOR_FILE) as f:
|
| 76 |
+
d = json.load(f)
|
| 77 |
+
q = {s: [float(v) for v in d[s]] for s in SIDES}
|
| 78 |
+
if any(len(q[s]) != 7 for s in SIDES):
|
| 79 |
+
raise ValueError("expected 7 joint angles")
|
| 80 |
+
g = {s: float(d.get(s + "_grip", 0.0)) for s in SIDES}
|
| 81 |
+
log.info("anchor loaded from %s", ANCHOR_FILE)
|
| 82 |
+
return q, g
|
| 83 |
+
except Exception as e: # noqa: BLE001
|
| 84 |
+
log.warning("failed to read anchor file (%s: %s); need --anchor-deg-left/right or %s",
|
| 85 |
+
type(e).__name__, e, ANCHOR_FILE)
|
| 86 |
+
return None, {"left": 0.0, "right": 0.0}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
ANCHOR_DEG, ANCHOR_GRIP_FROM_FILE = load_anchor()
|
| 90 |
+
# Gripper opening at the anchor (dataset scale, deg). The gripper is an observed column too,
|
| 91 |
+
# so a random start value is out of distribution from the first frame.
|
| 92 |
+
# Measured on the training set: grippers start almost closed (first-frame median ~0.2-0.3 deg).
|
| 93 |
+
ANCHOR_GRIP_DEG = ANCHOR_GRIP_FROM_FILE
|
| 94 |
+
|
| 95 |
+
# ---- Gripper ------------------------------------------------------------------------
|
| 96 |
+
GRIP_CALIB = os.environ.get("FLEXIV_GRIP_CALIB", os.path.join(DATA_DIR, "gripper_calib.json"))
|
| 97 |
+
# Calibrated mechanical travel is 0-90 deg (90 = fully open). Clamping to that range only
|
| 98 |
+
# rejects outliers beyond the mechanical limit; it does not narrow the model's range.
|
| 99 |
+
# (Training-data gripper range is roughly -1.6..17 deg, so the clamp rarely matters.)
|
| 100 |
+
# Command lower bound: let negative openings through (= "slightly past the calibrated closed
|
| 101 |
+
# position"). The model does output small negative values (down to about -0.3 deg); clamping
|
| 102 |
+
# at 0 would drop them. -2.0 covers the training range plus margin; this is pass-through.
|
| 103 |
+
# NOTE: passing them through does not mean a firm grip: -0.3 deg x kp36 is only ~0.18 Nm.
|
| 104 |
+
# The model carries no force information (labels only see opening angle).
|
| 105 |
+
# Constant offset subtracted from every model opening before execution.
|
| 106 |
+
# Rationale: without it the model never asks for enough squeeze to hold an object. With a
|
| 107 |
+
# 3 deg offset the error hits the lead=5 deg clamp when grasping -> force capped at
|
| 108 |
+
# kp*rad(5) = 3.14 Nm.
|
| 109 |
+
# WARNING: this shifts the position target, so open commands also shrink by 3 deg, and model
|
| 110 |
+
# openings below 3 deg push an empty gripper into the soft limit (stall up to 3.14 Nm, heats).
|
| 111 |
+
GRIP_OFFSET_DEG = float(os.environ.get("FLEXIV_GRIP_OFFSET_DEG", "3.0"))
|
| 112 |
+
# Reach scaling: step position = start + k*(model target - start), start = measured position at
|
| 113 |
+
# observation time; orientation unchanged. Default 1.0 = off. Scaled targets still go through
|
| 114 |
+
# the pre-checks (IK / limits / collision).
|
| 115 |
+
REACH_SCALE = {"left": 1.0, "right": float(os.environ.get("FLEXIV_REACH_SCALE_RIGHT", "1.0"))}
|
| 116 |
+
# Command lower bound must accommodate -(offset), otherwise the offset is silently clamped away.
|
| 117 |
+
GRIP_CMD_MIN_DEG = float(os.environ.get(
|
| 118 |
+
"FLEXIV_GRIP_CMD_MIN_DEG", "%.3f" % (-(GRIP_OFFSET_DEG + 2.0))))
|
| 119 |
+
GRIP_MAX_DEG = float(os.environ.get("FLEXIV_GRIP_MAX_DEG", "90.0"))
|
| 120 |
+
|
| 121 |
+
# Joint hard limits from the robot's info() (deg), same as kin_flexiv.py (5 deg narrower than URDF).
|
| 122 |
+
# Postures at the limit are rejected by SetNullSpacePosture ("outside the valid range"), so keep a margin.
|
| 123 |
+
RQMIN = np.array([-160., -130., -170., -107., -170., -80., -170.])
|
| 124 |
+
RQMAX = np.array([160., 130., 170., 154., 170., 260., 170.])
|
| 125 |
+
ANCHOR_MARGIN_DEG = float(os.environ.get("FLEXIV_ANCHOR_MARGIN_DEG", "0.5"))
|
| 126 |
+
|
| 127 |
+
# ---------------------------------------------------------------- prev selection (train/infer consistency)
|
| 128 |
+
# Native fps = dataset fps (30). Progress counting and prev lookback are in native frames, so
|
| 129 |
+
# slow-motion playback is absorbed automatically (at 4x slow, one native frame ~ 133 ms wall).
|
| 130 |
+
NATIVE_FPS = float(os.environ.get("FLEXIV_NATIVE_FPS", "30.0"))
|
| 131 |
+
# Max allowed deviation (native frames) when finding prev by progress; beyond it, fall back to wall clock.
|
| 132 |
+
PROGRESS_MAX_GAP_F = float(os.environ.get("FLEXIV_PROGRESS_MAX_GAP", "0.3"))
|
| 133 |
+
# 1 = look back by executed progress (default); 0 = by wall-clock time (old behavior, for A/B)
|
| 134 |
+
PREV_BY_PROGRESS = bool(int(os.environ.get("FLEXIV_PREV_BY_PROGRESS", "1")))
|
| 135 |
+
# 10th percentile of per-frame motion in the training set:
|
| 136 |
+
# translation p10=0.213mm median=1.419mm rotation p10=0.090deg median=0.381deg
|
| 137 |
+
# Warn when observed motion is below this; warning only, no behavior change.
|
| 138 |
+
TRAIN_P10_MM = float(os.environ.get("FLEXIV_TRAIN_P10_MM", "0.213"))
|
| 139 |
+
TRAIN_P10_DEG = float(os.environ.get("FLEXIV_TRAIN_P10_DEG", "0.090"))
|
| 140 |
+
# Lower bound of the gripper value *reported to the model*, separate from the command bound.
|
| 141 |
+
# If commands are ever pushed further negative to squeeze harder, the reported value must not
|
| 142 |
+
# follow: the model would see out-of-distribution values, keep asking to close, and the
|
| 143 |
+
# gripper would never reopen (positive feedback).
|
| 144 |
+
# How long to keep logging phase=hold rows after a chunk finishes (settling error). In sync mode inference is usually slower.
|
| 145 |
+
HOLD_ROW_S = 0.3
|
| 146 |
+
GRIP_OBS_MIN_DEG = float(os.environ.get("FLEXIV_GRIP_OBS_MIN_DEG", "-2.0"))
|
| 147 |
+
# Legacy alias
|
| 148 |
+
GRIP_MIN_DEG = GRIP_CMD_MIN_DEG
|
| 149 |
+
|
| 150 |
+
# ================================ pose7 layout conversion ================================
|
| 151 |
+
# Flexiv: [x,y,z, qw,qx,qy,qz] protocol/umi_decode: [x,y,z, qx,qy,qz,qw]
|
| 152 |
+
# Convert only in these two functions; a missing or double conversion looks like a calibration error.
|
| 153 |
+
def _w2x(p7) -> np.ndarray:
|
| 154 |
+
"""Flexiv wxyz -> protocol xyzw."""
|
| 155 |
+
p = np.asarray(p7, float).reshape(7)
|
| 156 |
+
return np.concatenate([p[:3], p[[4, 5, 6, 3]]])
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _x2w(p7) -> np.ndarray:
|
| 160 |
+
"""Protocol xyzw -> Flexiv wxyz (normalizes the quaternion; commands must be unit quaternions)."""
|
| 161 |
+
p = np.asarray(p7, float).reshape(7)
|
| 162 |
+
q = p[[6, 3, 4, 5]]
|
| 163 |
+
n = float(np.linalg.norm(q))
|
| 164 |
+
if not np.isfinite(n) or n < 1e-9:
|
| 165 |
+
raise ValueError("invalid quaternion: %s" % p[3:7].tolist())
|
| 166 |
+
return np.concatenate([p[:3], q / n])
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def trace_path(record_path: str) -> str:
|
| 170 |
+
"""Per-chunk trace path: x.csv -> x.chunks.jsonl."""
|
| 171 |
+
return os.path.splitext(record_path)[0] + ".chunks.jsonl"
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@dataclass
|
| 175 |
+
class _Buf:
|
| 176 |
+
"""Execution state of one action chunk in the servo thread."""
|
| 177 |
+
pose_w: np.ndarray # (M, 2, 7) Flexiv wxyz, shared world frame
|
| 178 |
+
twist: np.ndarray # (M, 2, 6) feedforward twist [v, w]
|
| 179 |
+
grip: np.ndarray # (M, 2) gripper opening, dataset scale
|
| 180 |
+
dt: float
|
| 181 |
+
start: float # perf_counter reference
|
| 182 |
+
seq: int
|
| 183 |
+
n_ik_bad: int = 0
|
| 184 |
+
truncated_from: int = 0
|
| 185 |
+
meta: dict = field(default_factory=dict)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class FlexivRobotIO(RobotIO):
|
| 189 |
+
def __init__(
|
| 190 |
+
self,
|
| 191 |
+
left_sn: str = DEFAULT_SN["left"],
|
| 192 |
+
right_sn: str = DEFAULT_SN["right"],
|
| 193 |
+
urdf: str = DEFAULT_URDF,
|
| 194 |
+
dry_run: bool = True,
|
| 195 |
+
servo_rate_hz: float = 100.0,
|
| 196 |
+
pose_dt: float = 0.033,
|
| 197 |
+
play_scale: float = 2.5,
|
| 198 |
+
max_stale_s: float = 2.0,
|
| 199 |
+
record_path: Optional[str] = None,
|
| 200 |
+
live_camera: bool = False,
|
| 201 |
+
jpeg_quality: int = 90,
|
| 202 |
+
cam_format: str = "jpeg",
|
| 203 |
+
cam_kbps: int = 512,
|
| 204 |
+
gripper: bool = False,
|
| 205 |
+
grip_calib: str = GRIP_CALIB,
|
| 206 |
+
grip_kp: float = 36.0,
|
| 207 |
+
grip_kd: float = 0.8,
|
| 208 |
+
grip_lead_deg: float = 5.0,
|
| 209 |
+
grip_rate_hz: float = 200.0,
|
| 210 |
+
anchor_deg: Optional[Dict[str, List[float]]] = None,
|
| 211 |
+
anchor_grip_deg: Optional[Dict[str, float]] = None,
|
| 212 |
+
# Safety: three distance guards, each covering part of the problem:
|
| 213 |
+
# monitor_min_dist link<->link (Flexiv monitor, real time, cannot see the grippers)
|
| 214 |
+
# min_dist measured TCP<->TCP (our per-cycle check)
|
| 215 |
+
# tool_min_dist 6 end-effector rigid points (our pre-send check; the only one that sees the grippers)
|
| 216 |
+
monitor_min_dist: float = 0.05,
|
| 217 |
+
min_dist: float = 0.02,
|
| 218 |
+
tool_min_dist: float = 0.02,
|
| 219 |
+
max_step_mm: float = 60.0,
|
| 220 |
+
ik_check: str = "truncate", # off | warn | truncate | abort
|
| 221 |
+
ik_max_calls: int = 24, # max reachable() calls per chunk (~6.4 ms each)
|
| 222 |
+
no_monitor: bool = False,
|
| 223 |
+
# impedance / speed limits
|
| 224 |
+
kx_ratio: float = 0.6,
|
| 225 |
+
zx: float = 0.7,
|
| 226 |
+
max_contact_wrench=(40.0, 40.0, 40.0, 10.0, 10.0, 10.0),
|
| 227 |
+
max_lin_vel: float = 0.5,
|
| 228 |
+
max_ang_vel: float = 1.5,
|
| 229 |
+
max_lin_acc: float = 2.0,
|
| 230 |
+
max_ang_acc: float = 5.0,
|
| 231 |
+
feedforward: bool = True,
|
| 232 |
+
# steps executed per chunk (first N of the model output; 0 = all). First chunk set separately
|
| 233 |
+
first_steps: int = 0,
|
| 234 |
+
steps: int = 0,
|
| 235 |
+
# Null-space (elbow) pull toward the reference posture, SDK range [0.1, 1.0].
|
| 236 |
+
# kx only covers the 6 end-effector DoF; the redundant elbow DoF is governed by this alone
|
| 237 |
+
nullspace_weight: float = 0.5,
|
| 238 |
+
# per-frame rollout recording (rollout_rec.py): root dir, empty = off; live wrist frame rate (0 = model inputs only)
|
| 239 |
+
rollout_root: Optional[str] = None,
|
| 240 |
+
rollout_cam_hz: float = 10.0,
|
| 241 |
+
):
|
| 242 |
+
self.sn = {"left": left_sn, "right": right_sn}
|
| 243 |
+
if not all(self.sn.values()) or not urdf:
|
| 244 |
+
raise ValueError("need both arm serial numbers "
|
| 245 |
+
"(--left-sn/--right-sn or FLEXIV_LEFT_SN/FLEXIV_RIGHT_SN)")
|
| 246 |
+
self.urdf = urdf
|
| 247 |
+
self.dry_run = bool(dry_run)
|
| 248 |
+
self.servo_rate_hz = float(servo_rate_hz)
|
| 249 |
+
self.pose_dt = float(pose_dt)
|
| 250 |
+
# Playback slowdown: each step is stretched by this factor in wall time. dt itself is
|
| 251 |
+
# unchanged (it is the dataset frame length; progress and prev lookback depend on it).
|
| 252 |
+
# Default 2.5: at 1x ~30% of trajectory points exceed max_linear_acc=2.0; slowing by k
|
| 253 |
+
# cuts acceleration by k^2, and at 2.5 the peak (1.72) stays under the limit.
|
| 254 |
+
self.play_scale = max(1.0, float(play_scale))
|
| 255 |
+
self.max_stale_s = float(max_stale_s)
|
| 256 |
+
self.record_path = record_path
|
| 257 |
+
self.live_camera = bool(live_camera)
|
| 258 |
+
self.jpeg_quality = int(jpeg_quality)
|
| 259 |
+
# jpeg: legacy path. yuv420p: send decoded I420 planes; the policy side converts to RGB and
|
| 260 |
+
# resizes with the same pyav call as training (no lossy JPEG, one less color conversion).
|
| 261 |
+
if cam_format not in ("jpeg", "yuv420p"):
|
| 262 |
+
raise ValueError("cam_format must be jpeg / yuv420p: %r" % cam_format)
|
| 263 |
+
self.cam_format = cam_format
|
| 264 |
+
# Live stream bitrate (full dual-fisheye frame, kbps). 512 is ~256 kbps per lens, far below
|
| 265 |
+
# the training videos (~8.7 Mbps AV1 per 960x960 view).
|
| 266 |
+
self.cam_kbps = int(cam_kbps)
|
| 267 |
+
self.use_gripper = bool(gripper)
|
| 268 |
+
self.grip_cfg = dict(calib=grip_calib, kp=grip_kp, kd=grip_kd,
|
| 269 |
+
lead_deg=grip_lead_deg, rate_hz=grip_rate_hz)
|
| 270 |
+
self.monitor_min_dist = float(monitor_min_dist)
|
| 271 |
+
self.min_dist = float(min_dist)
|
| 272 |
+
self.tool_min_dist = float(tool_min_dist)
|
| 273 |
+
self.max_step_mm = float(max_step_mm)
|
| 274 |
+
self.ik_check = str(ik_check).lower()
|
| 275 |
+
self.ik_max_calls = max(2, int(ik_max_calls))
|
| 276 |
+
self.no_monitor = bool(no_monitor)
|
| 277 |
+
self.kx_ratio, self.zx = float(kx_ratio), float(zx)
|
| 278 |
+
self.max_contact_wrench = list(max_contact_wrench)
|
| 279 |
+
self.vel_caps = dict(max_linear_vel=(max_lin_vel,) * 2,
|
| 280 |
+
max_angular_vel=(max_ang_vel,) * 2,
|
| 281 |
+
max_linear_acc=(max_lin_acc,) * 2,
|
| 282 |
+
max_angular_acc=(max_ang_acc,) * 2)
|
| 283 |
+
self.feedforward = bool(feedforward)
|
| 284 |
+
self.first_steps, self.steps = max(0, int(first_steps)), max(0, int(steps))
|
| 285 |
+
self.ns_weight = float(nullspace_weight)
|
| 286 |
+
if not 0.1 <= self.ns_weight <= 1.0:
|
| 287 |
+
raise ValueError("nullspace_weight must be in [0.1, 1.0]")
|
| 288 |
+
if self.ik_check not in ("off", "warn", "truncate", "abort"):
|
| 289 |
+
raise ValueError("ik_check must be off/warn/truncate/abort")
|
| 290 |
+
|
| 291 |
+
self._lt = None # pose_math module
|
| 292 |
+
self._pair = None
|
| 293 |
+
self._monitor = None
|
| 294 |
+
self._grip = None
|
| 295 |
+
self._dual = None
|
| 296 |
+
self._models = {} # side -> flexivrdk.Model (Flexiv IK, pre-check only)
|
| 297 |
+
self._bridge = {} # side -> T_world_sdkbase (pre-check maps world to per-arm base)
|
| 298 |
+
self._tool_X = None # tool rigid points in TCP frame, for the tool-aware pre-check
|
| 299 |
+
|
| 300 |
+
self._seq = 0
|
| 301 |
+
self._obs_pos = {} # obs seq -> {side: measured world position}, origin for reach scaling
|
| 302 |
+
self._buf: Optional[_Buf] = None
|
| 303 |
+
self._lock = threading.Lock() # guards _buf / cached state / history
|
| 304 |
+
self._stop_ev = threading.Event()
|
| 305 |
+
self._servo = None
|
| 306 |
+
self._rec = self._rec_w = None
|
| 307 |
+
# Per-chunk trace (<record>.chunks.jsonl): raw model output / IK solution / truncation,
|
| 308 |
+
# complements the per-step cmd/act CSV. Written by both apply_action and the servo thread
|
| 309 |
+
self._trace = None
|
| 310 |
+
self._trace_lock = threading.Lock()
|
| 311 |
+
self._ik_trace = None # IK samples from the last _precheck
|
| 312 |
+
self.rollout_root, self.rollout_cam_hz = rollout_root, float(rollout_cam_hz)
|
| 313 |
+
self._rollout = None # RolloutRecorder; opened in start(), closed in stop()
|
| 314 |
+
self._rollout_actions = True # stop calling actions() for q_d after the first failure
|
| 315 |
+
|
| 316 |
+
# Latest state cached by the servo thread. get_observation reads only this and never
|
| 317 |
+
# touches the SDK (RobotPair is not guaranteed thread-safe).
|
| 318 |
+
self._st_pose_w = {s: None for s in SIDES} # Flexiv wxyz
|
| 319 |
+
self._st_q = {s: None for s in SIDES}
|
| 320 |
+
self._st_t = 0.0
|
| 321 |
+
# Continuous history [(t, progress, {side: pose_w}, {side: grip_raw})].
|
| 322 |
+
# progress = native frames executed so far; prev is looked up by it.
|
| 323 |
+
self._hist: List = []
|
| 324 |
+
self._plan_progress = 0.0 # executed trajectory progress, in native frames
|
| 325 |
+
self._plan_knot_last = None # knot of the last sent step; None = rebuild baseline
|
| 326 |
+
self._prev_by_progress = PREV_BY_PROGRESS
|
| 327 |
+
self._degen_warn = 0.0 # throttle timestamp for low-motion warning
|
| 328 |
+
self._stale_obs_warn = 0.0 # throttle timestamp for stale-state warning
|
| 329 |
+
self._last_cmd_w = None # (2,7) last command sent
|
| 330 |
+
self._anchor_w = {} # anchor poses (world, wxyz)
|
| 331 |
+
self._anchor_q = None
|
| 332 |
+
self._grip_ds = {s: 0.0 for s in SIDES}
|
| 333 |
+
# range of model gripper commands, diagnostics only (is there any open/close signal?); no decisions use it
|
| 334 |
+
self._grip_seen = {"lo": {s: float("inf") for s in SIDES},
|
| 335 |
+
"hi": {s: float("-inf") for s in SIDES}}
|
| 336 |
+
self._last_ik_q = None # chained seed for the reachability pre-check
|
| 337 |
+
self._ik_warned = False
|
| 338 |
+
self._stale_warn = 0.0
|
| 339 |
+
self._health = {"chunks": 0, "ik_bad": 0, "truncated": 0, "rejected": 0,
|
| 340 |
+
"min_pair_m": np.inf, "abort": None}
|
| 341 |
+
self.anchor_deg = anchor_deg
|
| 342 |
+
self.anchor_grip_deg = dict(anchor_grip_deg or ANCHOR_GRIP_DEG)
|
| 343 |
+
|
| 344 |
+
# ------------------------------------------------------------------ helpers
|
| 345 |
+
def _pair_t(self, d):
|
| 346 |
+
"""{side: x} -> (left, right)."""
|
| 347 |
+
return (d["left"], d["right"])
|
| 348 |
+
|
| 349 |
+
def _sd(self, t):
|
| 350 |
+
"""DRDK (left, right) -> {side: x}."""
|
| 351 |
+
return {"left": t[0], "right": t[1]}
|
| 352 |
+
|
| 353 |
+
def _load_lt(self):
|
| 354 |
+
if self._lt is None:
|
| 355 |
+
from . import pose_math
|
| 356 |
+
self._lt = pose_math
|
| 357 |
+
return self._lt
|
| 358 |
+
|
| 359 |
+
def _anchor_q_rad(self):
|
| 360 |
+
"""Start posture (data/anchor.json or CLI). Per side: the two arms may differ."""
|
| 361 |
+
src = self.anchor_deg or ANCHOR_DEG
|
| 362 |
+
if src is None:
|
| 363 |
+
raise RuntimeError("no start posture: write %s (see configs/anchor.example.json) "
|
| 364 |
+
"or pass --anchor-deg-left/--anchor-deg-right" % ANCHOR_FILE)
|
| 365 |
+
for side in SIDES:
|
| 366 |
+
q = np.asarray(src[side], float)
|
| 367 |
+
lo, hi = q - RQMIN, RQMAX - q
|
| 368 |
+
m = float(min(lo.min(), hi.min()))
|
| 369 |
+
if m < ANCHOR_MARGIN_DEG:
|
| 370 |
+
bad = [("j%d=%.2fdeg (limit %.0f..%.0f, margin %.2fdeg)"
|
| 371 |
+
% (i + 1, q[i], RQMIN[i], RQMAX[i],
|
| 372 |
+
min(q[i] - RQMIN[i], RQMAX[i] - q[i])))
|
| 373 |
+
for i in range(7)
|
| 374 |
+
if min(q[i] - RQMIN[i], RQMAX[i] - q[i]) < ANCHOR_MARGIN_DEG]
|
| 375 |
+
raise ValueError(
|
| 376 |
+
"anchor[%s] too close to joint hard limit (margin %.2fdeg < %.2fdeg): %s\n"
|
| 377 |
+
" -> the robot will reject the null-space reference posture (SDK: 'outside the valid range'); "
|
| 378 |
+
"move that joint back by ~1 deg. Edit %s."
|
| 379 |
+
% (side, m, ANCHOR_MARGIN_DEG, "; ".join(bad), ANCHOR_FILE))
|
| 380 |
+
return {s: np.radians(src[s]) for s in SIDES}
|
| 381 |
+
|
| 382 |
+
# ------------------------------------------------------------------ lifecycle
|
| 383 |
+
def start(self) -> None:
|
| 384 |
+
import flexivdrdk
|
| 385 |
+
import flexivrdk
|
| 386 |
+
from flexivrdk import Mode
|
| 387 |
+
lt = self._load_lt()
|
| 388 |
+
self._Mode = Mode
|
| 389 |
+
self._CART = Mode.NRT_CARTESIAN_MOTION_FORCE
|
| 390 |
+
|
| 391 |
+
log.info("connecting arms: left %s | right %s (base world offset left %s right %s)",
|
| 392 |
+
self.sn["left"], self.sn["right"], lt.BASE_XYZ["left"], lt.BASE_XYZ["right"])
|
| 393 |
+
self._pair = flexivdrdk.RobotPair(
|
| 394 |
+
[self.sn["left"], self.sn["right"]],
|
| 395 |
+
[lt.BASE_XYZ["left"], lt.BASE_XYZ["right"]])
|
| 396 |
+
for s, info in self._sd(self._pair.info()).items():
|
| 397 |
+
log.info(" [%-5s] %s DoF=%d", s, info.model_name, info.DoF)
|
| 398 |
+
if info.DoF != ARM_DOF:
|
| 399 |
+
raise RuntimeError("%s arm DoF=%d; only 7-DoF arms without external axes are supported" % (s, info.DoF))
|
| 400 |
+
|
| 401 |
+
# Flexiv IK: build a Model from the pair's underlying Robots (no extra connection;
|
| 402 |
+
# RobotPair has no kinematics API, but instances() exposes the two Robots)
|
| 403 |
+
inst = self._sd(self._pair.instances())
|
| 404 |
+
for s in SIDES:
|
| 405 |
+
self._models[s] = flexivrdk.Model(inst[s])
|
| 406 |
+
log.info("kinematics models ready (pre-send reachability check only; the controller solves IK)")
|
| 407 |
+
|
| 408 |
+
if self.dry_run:
|
| 409 |
+
log.warning("DRY-RUN: full pipeline runs, but no motion commands are sent")
|
| 410 |
+
|
| 411 |
+
if not self.dry_run:
|
| 412 |
+
self._enable()
|
| 413 |
+
self._monitor = self._start_monitor()
|
| 414 |
+
|
| 415 |
+
# grippers: bring them up before the arms move (separate bus)
|
| 416 |
+
if self.use_gripper:
|
| 417 |
+
self._start_gripper()
|
| 418 |
+
|
| 419 |
+
if not self.dry_run:
|
| 420 |
+
self._move_to_anchor()
|
| 421 |
+
self._zero_ft()
|
| 422 |
+
log.info("switching to NRT_CARTESIAN_MOTION_FORCE (controller solves IK)...")
|
| 423 |
+
self._pair.SwitchMode(self._CART)
|
| 424 |
+
self._setup_impedance()
|
| 425 |
+
|
| 426 |
+
# anchor + bridge + tool geometry: all needed by the pre-checks
|
| 427 |
+
self._read_anchor()
|
| 428 |
+
self._measure_bridge()
|
| 429 |
+
self._prepare_tool_geometry()
|
| 430 |
+
self._selftest_quat()
|
| 431 |
+
self._selftest_reachable()
|
| 432 |
+
|
| 433 |
+
if self.live_camera:
|
| 434 |
+
self._start_cameras()
|
| 435 |
+
|
| 436 |
+
if self.record_path:
|
| 437 |
+
self._rec = open(self.record_path, "w", newline="", buffering=1) # line-buffered so it can be tailed live
|
| 438 |
+
cols = ["t", "seq", "idx", "phase"]
|
| 439 |
+
for s in SIDES:
|
| 440 |
+
cols += ["%s_cmd_%s" % (s, a) for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
|
| 441 |
+
cols += ["%s_act_%s" % (s, a) for a in ("x", "y", "z")]
|
| 442 |
+
cols += ["%s_grip_cmd" % s, "%s_grip_meas" % s]
|
| 443 |
+
cols += ["pair_dist_m"]
|
| 444 |
+
# measured orientation / joints appended at the end so positional readers keep working
|
| 445 |
+
for s in SIDES:
|
| 446 |
+
cols += ["%s_act_%s" % (s, a) for a in ("qw", "qx", "qy", "qz")]
|
| 447 |
+
for s in SIDES:
|
| 448 |
+
cols += ["%s_q%d" % (s, k) for k in range(1, ARM_DOF + 1)]
|
| 449 |
+
cols += ["knot"] # exact in-chunk progress of the servo (fractional step), for alignment
|
| 450 |
+
# External wrench (RDK ext_wrench_in_world / ext_wrench_in_tcp, N / Nm), to see whether
|
| 451 |
+
# max_contact_wrench was hit. Also appended at the end; nan if unavailable
|
| 452 |
+
for s in SIDES:
|
| 453 |
+
for fr in ("w", "tcp"):
|
| 454 |
+
cols += ["%s_ext%s_%s" % (s, fr, a) for a in ("fx", "fy", "fz", "mx", "my", "mz")]
|
| 455 |
+
self._rec_w = csv.writer(self._rec)
|
| 456 |
+
self._rec_w.writerow(cols)
|
| 457 |
+
self._trace = open(trace_path(self.record_path), "w", buffering=1)
|
| 458 |
+
self._trace_write({"event": "start", "dry_run": self.dry_run,
|
| 459 |
+
"play_scale": self.play_scale, "ik_check": self.ik_check,
|
| 460 |
+
"kx_ratio": self.kx_ratio, "zx": self.zx,
|
| 461 |
+
"nullspace_weight": self.ns_weight,
|
| 462 |
+
"first_steps": self.first_steps, "steps": self.steps,
|
| 463 |
+
"anchor": {s: self._anchor_w[s].tolist() for s in SIDES}})
|
| 464 |
+
self._open_rollout()
|
| 465 |
+
|
| 466 |
+
# initial buffer = hold at anchor (servo needs something to send before the first chunk)
|
| 467 |
+
pose0 = np.stack([self._anchor_w[s] for s in SIDES]) # (2,7)
|
| 468 |
+
with self._lock:
|
| 469 |
+
self._buf = _Buf(pose_w=pose0[None], twist=np.zeros((1, 2, 6)),
|
| 470 |
+
grip=np.zeros((1, 2)), dt=1.0 / self.servo_rate_hz,
|
| 471 |
+
start=time.perf_counter(), seq=-1,
|
| 472 |
+
meta={"anchor_hold": True})
|
| 473 |
+
self._last_cmd_w = pose0.copy()
|
| 474 |
+
|
| 475 |
+
if self.use_gripper:
|
| 476 |
+
log.info("gripper = model output minus %.1fdeg (command clamp [%.1f,%.0f]deg, report clamp "
|
| 477 |
+
"[%.1f,%.0f]deg, grasp force cap %.2f Nm)",
|
| 478 |
+
GRIP_OFFSET_DEG, GRIP_CMD_MIN_DEG, GRIP_MAX_DEG,
|
| 479 |
+
GRIP_OBS_MIN_DEG, GRIP_MAX_DEG,
|
| 480 |
+
self.grip_cfg["kp"] * np.radians(self.grip_cfg["lead_deg"]))
|
| 481 |
+
log.info(" WARNING: open commands also shrink by %.1fdeg; below %.1fdeg an empty gripper stalls at the soft limit (heats)",
|
| 482 |
+
GRIP_OFFSET_DEG, GRIP_OFFSET_DEG)
|
| 483 |
+
log.info(" NOTE: the calibrated closed position was set at 0.52 Nm (calib meta), so a 0deg command"
|
| 484 |
+
" is only a light touch")
|
| 485 |
+
|
| 486 |
+
self._servo = threading.Thread(target=self._servo_loop, daemon=True)
|
| 487 |
+
self._servo.start()
|
| 488 |
+
log.info("FlexivRobotIO ready (dry_run=%s servo=%.0fHz playback=%.2fx slower gripper=%s camera=%s)",
|
| 489 |
+
self.dry_run, self.servo_rate_hz, self.play_scale,
|
| 490 |
+
self.use_gripper, self.live_camera)
|
| 491 |
+
log.info(" steps per chunk: first %s / then %s (first N of the model output)",
|
| 492 |
+
self.first_steps or "all", self.steps or "all")
|
| 493 |
+
log.info(" playback x%.2f: %.4fs per step (wall), velocity /%.2f, acceleration /%.2f "
|
| 494 |
+
"(at 1x ~30%% of points exceed max_linear_acc=2.0)",
|
| 495 |
+
self.play_scale, self.pose_dt * self.play_scale,
|
| 496 |
+
self.play_scale, self.play_scale ** 2)
|
| 497 |
+
log.info(" prev lookup = %s (back %.0f native frames @ %.0fHz, tolerance %.1f frames)",
|
| 498 |
+
"by executed progress" if self._prev_by_progress else "by wall clock (old behavior)",
|
| 499 |
+
max(1.0, round(self.pose_dt * NATIVE_FPS)), NATIVE_FPS,
|
| 500 |
+
PROGRESS_MAX_GAP_F)
|
| 501 |
+
|
| 502 |
+
def stop(self) -> None:
|
| 503 |
+
self._stop_ev.set()
|
| 504 |
+
if self._servo:
|
| 505 |
+
self._servo.join(timeout=3.0)
|
| 506 |
+
if self._rollout is not None:
|
| 507 |
+
self._rollout.stop_cameras() # stop grab threads before cameras close
|
| 508 |
+
if self._pair is not None and not self.dry_run:
|
| 509 |
+
try:
|
| 510 |
+
if self._pair.operational():
|
| 511 |
+
self._pair.Stop()
|
| 512 |
+
t0 = time.time()
|
| 513 |
+
while not self._pair.stopped() and time.time() - t0 < 5.0:
|
| 514 |
+
time.sleep(0.1)
|
| 515 |
+
except Exception as e: # noqa: BLE001
|
| 516 |
+
log.error("Stop() failed: %s", e)
|
| 517 |
+
if self._grip is not None:
|
| 518 |
+
try:
|
| 519 |
+
self._grip.close() # release torque + disable, fingers back-drivable
|
| 520 |
+
except Exception as e: # noqa: BLE001
|
| 521 |
+
log.error("gripper shutdown failed: %s", e)
|
| 522 |
+
if self._monitor is not None:
|
| 523 |
+
try:
|
| 524 |
+
self._monitor.Stop()
|
| 525 |
+
except Exception: # noqa: BLE001
|
| 526 |
+
pass
|
| 527 |
+
if self._dual is not None:
|
| 528 |
+
try:
|
| 529 |
+
self._dual.stop()
|
| 530 |
+
except Exception: # noqa: BLE001
|
| 531 |
+
pass
|
| 532 |
+
if self._rec:
|
| 533 |
+
self._rec.close()
|
| 534 |
+
h = self._health
|
| 535 |
+
self._trace_write({"event": "stop", "chunks": h["chunks"], "ik_bad": h["ik_bad"],
|
| 536 |
+
"truncated": h["truncated"], "rejected": h["rejected"],
|
| 537 |
+
"abort": h["abort"]})
|
| 538 |
+
if self._trace:
|
| 539 |
+
with self._trace_lock:
|
| 540 |
+
self._trace.close()
|
| 541 |
+
self._trace = None
|
| 542 |
+
if self._rollout is not None:
|
| 543 |
+
self._rollout.close() # drain queue + write summary.json
|
| 544 |
+
self._rollout = None
|
| 545 |
+
log.info("summary: chunks %d, unreachable steps %d, truncated %d, rejected %d, "
|
| 546 |
+
"min arm distance %.3f m%s",
|
| 547 |
+
h["chunks"], h["ik_bad"], h["truncated"], h["rejected"],
|
| 548 |
+
h["min_pair_m"],
|
| 549 |
+
(" abort reason: " + h["abort"]) if h["abort"] else "")
|
| 550 |
+
if self.use_gripper and all(
|
| 551 |
+
self._grip_seen["hi"][s] > self._grip_seen["lo"][s] for s in SIDES):
|
| 552 |
+
for s in SIDES:
|
| 553 |
+
lo, hi = self._grip_seen["lo"][s], self._grip_seen["hi"][s]
|
| 554 |
+
log.info(" gripper[%s] raw model output %.2f ~ %.2fdeg (span %.2fdeg) "
|
| 555 |
+
"-> minus %.1fdeg, sent %.2f ~ %.2fdeg",
|
| 556 |
+
s, lo, hi, hi - lo, GRIP_OFFSET_DEG,
|
| 557 |
+
max(lo - GRIP_OFFSET_DEG, GRIP_CMD_MIN_DEG),
|
| 558 |
+
min(hi - GRIP_OFFSET_DEG, GRIP_MAX_DEG))
|
| 559 |
+
|
| 560 |
+
# ------------------------------------------------------------------ enable / safety
|
| 561 |
+
def _open_rollout(self) -> None:
|
| 562 |
+
"""Open per-frame rollout recording (off if rollout_root is empty). Failures only warn."""
|
| 563 |
+
if not self.rollout_root:
|
| 564 |
+
return
|
| 565 |
+
from .rollout_rec import open_recorder
|
| 566 |
+
qmin = {s: RQMIN.copy() for s in SIDES}
|
| 567 |
+
qmax = {s: RQMAX.copy() for s in SIDES}
|
| 568 |
+
info = {}
|
| 569 |
+
try:
|
| 570 |
+
# prefer limits reported by the robot (RobotInfo.q_min/q_max, rad); fall back to RQMIN/RQMAX
|
| 571 |
+
info = self._sd(self._pair.info())
|
| 572 |
+
for s in SIDES:
|
| 573 |
+
lo = np.degrees(np.asarray(info[s].q_min, float))
|
| 574 |
+
hi = np.degrees(np.asarray(info[s].q_max, float))
|
| 575 |
+
if lo.shape == (ARM_DOF,) and hi.shape == (ARM_DOF,) and np.isfinite([lo, hi]).all():
|
| 576 |
+
qmin[s], qmax[s] = lo, hi
|
| 577 |
+
except Exception as e: # noqa: BLE001
|
| 578 |
+
log.warning("rollout: failed to read RobotInfo limits (%s), using RQMIN/RQMAX", e)
|
| 579 |
+
cam_hz = self.rollout_cam_hz if self._dual is not None else 0.0
|
| 580 |
+
self._rollout = open_recorder(self.rollout_root, tag="dry" if self.dry_run else "live",
|
| 581 |
+
cam_hz=cam_hz, q_min_deg=qmin, q_max_deg=qmax)
|
| 582 |
+
if self._rollout is None:
|
| 583 |
+
return
|
| 584 |
+
K = {}
|
| 585 |
+
for s, inf in (info or {}).items():
|
| 586 |
+
try:
|
| 587 |
+
K[s] = (np.asarray(inf.K_x_nom, float) * self.kx_ratio).tolist()
|
| 588 |
+
except Exception: # noqa: BLE001
|
| 589 |
+
pass
|
| 590 |
+
anchor_q = getattr(self, "_anchor_q", None) or {}
|
| 591 |
+
self._rollout.write_meta({
|
| 592 |
+
"started": time.strftime("%Y-%m-%d %H:%M:%S"), "argv": sys.argv,
|
| 593 |
+
"dry_run": self.dry_run, "sn": self.sn, "servo_rate_hz": self.servo_rate_hz,
|
| 594 |
+
"pose_dt": self.pose_dt, "play_scale": self.play_scale,
|
| 595 |
+
"kx_ratio": self.kx_ratio, "zx": self.zx, "K_x": K,
|
| 596 |
+
"nullspace_weight": self.ns_weight, "max_contact_wrench": self.max_contact_wrench,
|
| 597 |
+
"vel_caps": self.vel_caps, "feedforward": self.feedforward,
|
| 598 |
+
"first_steps": self.first_steps, "steps": self.steps, "ik_check": self.ik_check,
|
| 599 |
+
"max_step_mm": self.max_step_mm, "min_dist": self.min_dist,
|
| 600 |
+
"tool_min_dist": self.tool_min_dist, "cam_format": self.cam_format,
|
| 601 |
+
"cam_kbps": self.cam_kbps, "gripper": self.use_gripper,
|
| 602 |
+
"grip_offset_deg": GRIP_OFFSET_DEG, "prev_by_progress": self._prev_by_progress,
|
| 603 |
+
"record_path": self.record_path,
|
| 604 |
+
"anchor_w": {s: np.asarray(v).tolist() for s, v in self._anchor_w.items()},
|
| 605 |
+
"anchor_q_deg": {s: np.degrees(np.asarray(v, float)).tolist()
|
| 606 |
+
for s, v in anchor_q.items()},
|
| 607 |
+
})
|
| 608 |
+
if cam_hz > 0:
|
| 609 |
+
self._rollout.start_cameras(self._dual.get_frame)
|
| 610 |
+
log.info("rollout recording -> %s (live wrist frames %.0fHz, limit warning <%.1fdeg)",
|
| 611 |
+
self._rollout.dir, cam_hz, float(os.environ.get("FLEXIV_ROLLOUT_LIMIT_DEG", "3.0")))
|
| 612 |
+
|
| 613 |
+
def _rollout_servo(self, st, pose_w, q, cmd, buf, i, n, phase, hold, sent, pair_d, t_cycle):
|
| 614 |
+
"""Hand one servo row to the rollout recorder. Controller targets (q_d / tcp_pose_d) are only read when recording."""
|
| 615 |
+
des, q_d = {}, {}
|
| 616 |
+
if self._rollout_actions:
|
| 617 |
+
try:
|
| 618 |
+
ac = self._sd(self._pair.actions())
|
| 619 |
+
for s in SIDES:
|
| 620 |
+
des[s] = np.asarray(ac[s].tcp_pose_d, float)
|
| 621 |
+
q_d[s] = np.asarray(ac[s].q_d, float)
|
| 622 |
+
except Exception as e: # noqa: BLE001
|
| 623 |
+
self._rollout_actions = False
|
| 624 |
+
log.warning("rollout: reading actions().q_d failed (%s: %s); des/q_d columns set to nan",
|
| 625 |
+
type(e).__name__, e)
|
| 626 |
+
tag = ("hold" if hold else "wait" if (buf.seq >= 0 and phase > n - 1)
|
| 627 |
+
else buf.meta.get("phase", "run"))
|
| 628 |
+
attr = lambda a: {s: getattr(st[s], a, None) for s in SIDES} # noqa: E731
|
| 629 |
+
self._rollout.servo(
|
| 630 |
+
t=time.time(), seq=buf.seq, idx=i, phase=tag, knot=float(np.clip(phase, 0.0, n - 1)),
|
| 631 |
+
sent=sent, cycle_ms=(time.perf_counter() - t_cycle) * 1000.0, pair_dist=pair_d,
|
| 632 |
+
cmd={s: cmd[IDX[s]] for s in SIDES}, des=des, act=pose_w, q=q, q_d=q_d,
|
| 633 |
+
dq=attr("dq"), tau=attr("tau"), tau_ext=attr("tau_ext"),
|
| 634 |
+
extw=attr("ext_wrench_in_world"), exttcp=attr("ext_wrench_in_tcp"),
|
| 635 |
+
grip_cmd={s: buf.grip[i, IDX[s]] for s in SIDES},
|
| 636 |
+
grip_meas={s: self._grip_ds[s] for s in SIDES})
|
| 637 |
+
|
| 638 |
+
def _trace_write(self, rec: dict) -> None:
|
| 639 |
+
"""Append one record to chunks.jsonl. Failures only warn and never affect control."""
|
| 640 |
+
if self._rollout is not None:
|
| 641 |
+
self._rollout.event(rec)
|
| 642 |
+
if self._trace is None:
|
| 643 |
+
return
|
| 644 |
+
rec = {"t": round(time.time(), 4), **rec}
|
| 645 |
+
try:
|
| 646 |
+
line = json.dumps(rec, ensure_ascii=False)
|
| 647 |
+
with self._trace_lock:
|
| 648 |
+
if self._trace is not None:
|
| 649 |
+
self._trace.write(line + "\n")
|
| 650 |
+
except (OSError, TypeError, ValueError) as e:
|
| 651 |
+
log.warning("trace write failed (%s): %s", type(e).__name__, e)
|
| 652 |
+
|
| 653 |
+
def _enable(self):
|
| 654 |
+
p = self._pair
|
| 655 |
+
if p.fault():
|
| 656 |
+
w = p.which_fault()
|
| 657 |
+
log.warning("fault detected (left=%s right=%s), trying to clear ...", w[0], w[1])
|
| 658 |
+
r = p.ClearFault()
|
| 659 |
+
if not (r[0] and r[1]):
|
| 660 |
+
raise RuntimeError("fault cannot be cleared; check Flexiv Elements")
|
| 661 |
+
if not all(p.estop_released()):
|
| 662 |
+
raise RuntimeError("E-stop engaged; release it first")
|
| 663 |
+
log.info("enabling arms ...")
|
| 664 |
+
p.Enable()
|
| 665 |
+
t0 = time.time()
|
| 666 |
+
while not p.operational():
|
| 667 |
+
if time.time() - t0 > 60.0:
|
| 668 |
+
import flexivrdk
|
| 669 |
+
st = self._sd(p.operational_status())
|
| 670 |
+
hint = ""
|
| 671 |
+
if any(v == flexivrdk.OperationalStatus.IN_MANUAL_MODE for v in st.values()):
|
| 672 |
+
hint = "; an arm is in manual mode, switch the mode selector to Auto"
|
| 673 |
+
raise RuntimeError("timed out waiting for operational: left=%s right=%s%s" % (st["left"], st["right"], hint))
|
| 674 |
+
time.sleep(0.5)
|
| 675 |
+
log.info("arms operational")
|
| 676 |
+
|
| 677 |
+
def _start_monitor(self):
|
| 678 |
+
import flexivdrdk
|
| 679 |
+
if self.no_monitor:
|
| 680 |
+
log.warning("self-collision monitor disabled: no link-distance protection!")
|
| 681 |
+
return None
|
| 682 |
+
m = flexivdrdk.SelfCollisionMonitor(self._pair, [])
|
| 683 |
+
m.SetMinDistance(self.monitor_min_dist)
|
| 684 |
+
m.Start(10)
|
| 685 |
+
log.info("self-collision monitor started: %.0f cm / 10 ms "
|
| 686 |
+
"(WARNING: arm links only, not the UMI grippers, which extend 161 mm past the flange; "
|
| 687 |
+
"at %.0f cm link distance the grippers may already touch; covered by the %.0f cm tool-aware pre-check)",
|
| 688 |
+
self.monitor_min_dist * 100, self.monitor_min_dist * 100,
|
| 689 |
+
self.tool_min_dist * 100)
|
| 690 |
+
log.info(" other guards: measured TCP<->TCP %.0f cm (per cycle) / tool-aware pre-check %.0f cm (before send)",
|
| 691 |
+
self.min_dist * 100, self.tool_min_dist * 100)
|
| 692 |
+
return m
|
| 693 |
+
|
| 694 |
+
def _move_to_anchor(self):
|
| 695 |
+
q_d = self._anchor_q_rad()
|
| 696 |
+
for s in SIDES:
|
| 697 |
+
log.info(" [%-5s] anchor joints [deg] = %s", s,
|
| 698 |
+
np.round(np.degrees(q_d[s]), 2).tolist())
|
| 699 |
+
z = [0.0] * ARM_DOF
|
| 700 |
+
self._pair.SwitchMode(self._Mode.NRT_JOINT_POSITION)
|
| 701 |
+
self._pair.SendJointPosition(
|
| 702 |
+
self._pair_t({s: q_d[s].tolist() for s in SIDES}), (z, z),
|
| 703 |
+
([0.3] * ARM_DOF,) * 2, ([0.8] * ARM_DOF,) * 2)
|
| 704 |
+
t0 = time.time()
|
| 705 |
+
while True:
|
| 706 |
+
st = self._sd(self._pair.states())
|
| 707 |
+
err = {s: float(np.abs(np.asarray(st[s].q) - q_d[s]).max()) for s in SIDES}
|
| 708 |
+
if max(err.values()) <= 0.01:
|
| 709 |
+
break
|
| 710 |
+
if self._pair.fault():
|
| 711 |
+
raise RuntimeError("fault while moving to anchor")
|
| 712 |
+
if time.time() - t0 > 90.0:
|
| 713 |
+
raise RuntimeError("timed out moving to anchor, residual [rad] left=%.4f right=%.4f"
|
| 714 |
+
% (err["left"], err["right"]))
|
| 715 |
+
time.sleep(0.05)
|
| 716 |
+
self._anchor_q = q_d
|
| 717 |
+
log.info("both arms at anchor")
|
| 718 |
+
|
| 719 |
+
def _zero_ft(self):
|
| 720 |
+
"""Force-control modes require ZeroFTSensor in this RDK session (otherwise error 301004)."""
|
| 721 |
+
log.info("zeroing wrist F/T sensor ...")
|
| 722 |
+
self._pair.SwitchMode(self._Mode.NRT_PRIMITIVE_EXECUTION)
|
| 723 |
+
self._pair.ExecutePrimitive(("ZeroFTSensor", "ZeroFTSensor"), (dict(), dict()))
|
| 724 |
+
t0 = time.time()
|
| 725 |
+
while not all(s["terminated"] for s in self._pair.primitive_states()):
|
| 726 |
+
if time.time() - t0 > 30.0:
|
| 727 |
+
raise RuntimeError("ZeroFTSensor timed out")
|
| 728 |
+
time.sleep(0.2)
|
| 729 |
+
log.info("wrist F/T sensor zeroed")
|
| 730 |
+
|
| 731 |
+
def _setup_impedance(self):
|
| 732 |
+
off = [False] * 6
|
| 733 |
+
self._pair.SetForceControlAxis((off, off)) # pure motion = Cartesian impedance tracking
|
| 734 |
+
K = {}
|
| 735 |
+
for s, info in self._sd(self._pair.info()).items():
|
| 736 |
+
nom = np.asarray(info.K_x_nom, float)
|
| 737 |
+
K[s] = nom * self.kx_ratio
|
| 738 |
+
log.info(" [%-5s] K_x = %s Z_x = %.2f", s, np.round(K[s], 1).tolist(), self.zx)
|
| 739 |
+
Z = [self.zx] * 6
|
| 740 |
+
self._pair.SetCartesianImpedance(
|
| 741 |
+
self._pair_t({s: K[s].tolist() for s in SIDES}), (Z, Z))
|
| 742 |
+
q_ns = self._anchor_q_rad()
|
| 743 |
+
self._pair.SetNullSpacePosture(
|
| 744 |
+
self._pair_t({s: np.asarray(q_ns[s]).tolist() for s in SIDES}))
|
| 745 |
+
# must be set after SwitchMode: re-entering the mode resets it to the default 0.5
|
| 746 |
+
w = self.ns_weight
|
| 747 |
+
self._pair.SetNullSpaceObjectives((0.0, 0.0), (0.0, 0.0), (w, w))
|
| 748 |
+
self._pair.SetMaxContactWrench((self.max_contact_wrench, self.max_contact_wrench))
|
| 749 |
+
log.info(" null-space reference = anchor, weight %.2f (0.1 soft / 0.5 default / 1.0 stiff); "
|
| 750 |
+
"max contact wrench = %s", w, self.max_contact_wrench)
|
| 751 |
+
|
| 752 |
+
# ------------------------------------------------------------------ anchor / bridge / tool
|
| 753 |
+
def _read_anchor(self):
|
| 754 |
+
"""Anchor pose P0 (shared world frame). In Cartesian mode prefer actions().tcp_pose_d."""
|
| 755 |
+
lt = self._load_lt()
|
| 756 |
+
time.sleep(0.5)
|
| 757 |
+
st = self._sd(self._pair.states())
|
| 758 |
+
src = "states"
|
| 759 |
+
pose = {s: lt.normalize_pose7(np.asarray(st[s].tcp_pose, float)) for s in SIDES}
|
| 760 |
+
if not self.dry_run:
|
| 761 |
+
ac = self._sd(self._pair.actions())
|
| 762 |
+
des = {s: np.asarray(ac[s].tcp_pose_d, float) for s in SIDES}
|
| 763 |
+
if all(abs(np.linalg.norm(des[s][3:7]) - 1.0) < 1e-3 for s in SIDES) and \
|
| 764 |
+
all(np.linalg.norm(des[s][:3] - pose[s][:3]) < 0.01 for s in SIDES):
|
| 765 |
+
pose = {s: lt.normalize_pose7(des[s]) for s in SIDES}
|
| 766 |
+
src = "actions"
|
| 767 |
+
self._anchor_w = pose
|
| 768 |
+
if self._anchor_q is None:
|
| 769 |
+
self._anchor_q = {s: np.asarray(st[s].q, float) for s in SIDES}
|
| 770 |
+
for s in SIDES:
|
| 771 |
+
p = pose[s]
|
| 772 |
+
log.info(" [%-5s] anchor P0 (world, from %s) xyz=[%+.4f %+.4f %+.4f] "
|
| 773 |
+
"quat_wxyz=[%+.4f %+.4f %+.4f %+.4f]", s, src, *p)
|
| 774 |
+
|
| 775 |
+
def _measure_bridge(self):
|
| 776 |
+
"""Measure T_world_sdkbase; Flexiv IK takes poses in the single-arm base frame.
|
| 777 |
+
|
| 778 |
+
URDF-independent: read the pair tcp_pose (world) and the single-arm tcp_pose (arm base)
|
| 779 |
+
at the same time, `T_world_sdkbase = T_world_tcp @ inv(T_sdkbase_tcp)`.
|
| 780 |
+
It must be a pure translation equal to BASE_XYZ; otherwise the frame convention changed, so fail.
|
| 781 |
+
"""
|
| 782 |
+
lt = self._load_lt()
|
| 783 |
+
from scipy.spatial.transform import Rotation as Rot
|
| 784 |
+
inst = self._sd(self._pair.instances())
|
| 785 |
+
st_w = self._sd(self._pair.states())
|
| 786 |
+
for s in SIDES:
|
| 787 |
+
T_w = lt.pose7_to_T(lt.normalize_pose7(np.asarray(st_w[s].tcp_pose, float)))
|
| 788 |
+
T_b = lt.pose7_to_T(lt.normalize_pose7(np.asarray(inst[s].states().tcp_pose, float)))
|
| 789 |
+
B = T_w @ np.linalg.inv(T_b)
|
| 790 |
+
rot_deg = float(np.degrees(np.linalg.norm(Rot.from_matrix(B[:3, :3]).as_rotvec())))
|
| 791 |
+
want = np.asarray(lt.BASE_XYZ[s], float)
|
| 792 |
+
dt_mm = float(np.linalg.norm(B[:3, 3] - want) * 1000)
|
| 793 |
+
log.info(" [%-5s] world<-arm base: translation %s m (expected %s, diff %.2f mm), rotation %.4fdeg",
|
| 794 |
+
s, np.round(B[:3, 3], 5).tolist(), want.tolist(), dt_mm, rot_deg)
|
| 795 |
+
if rot_deg > 0.5 or dt_mm > 5.0:
|
| 796 |
+
raise RuntimeError(
|
| 797 |
+
"%s arm world<->base bridge is not the expected pure translation (rotation %.3fdeg, translation diff %.1f mm); "
|
| 798 |
+
"frame convention changed and the reachability pre-check would be wrong" % (s, rot_deg, dt_mm))
|
| 799 |
+
self._bridge[s] = B
|
| 800 |
+
|
| 801 |
+
def _prepare_tool_geometry(self):
|
| 802 |
+
"""Rigid tool points for the gripper-aware arm distance pre-check.
|
| 803 |
+
|
| 804 |
+
FK uses kin_flexiv (yourdfpy, no PyBullet) on the same URDF and kinematics parameters
|
| 805 |
+
synced from the robot (SyncKinematicsYAML). The tool is rigidly fixed to the flange, so the
|
| 806 |
+
transform is joint-independent: compute it at q=0 and verify at a second posture.
|
| 807 |
+
"""
|
| 808 |
+
self._load_lt()
|
| 809 |
+
if self.tool_min_dist <= 0:
|
| 810 |
+
log.warning("tool_min_dist<=0: tool-aware distance pre-check disabled; the monitor cannot see the grippers (not recommended)")
|
| 811 |
+
return
|
| 812 |
+
lt = self._lt
|
| 813 |
+
try:
|
| 814 |
+
from . import kin_flexiv as K
|
| 815 |
+
links = list(lt.DEFAULT_TOOL_LINKS)
|
| 816 |
+
arms = {s: K.Arm(s, urdf=self.urdf, robot=False, verbose=False,
|
| 817 |
+
pre=K.prefix(s, self.sn[s])) for s in SIDES}
|
| 818 |
+
q0 = np.zeros(7)
|
| 819 |
+
q1 = np.radians([25., 50., -35., 95., 15., 70., -40.]) # check joint independence
|
| 820 |
+
out, drift = {}, 0.0
|
| 821 |
+
for lk in links:
|
| 822 |
+
out[lk] = {}
|
| 823 |
+
for s in SIDES:
|
| 824 |
+
inv0 = np.linalg.inv(arms[s].fk(q0, "flange"))
|
| 825 |
+
X0 = inv0 @ arms[s].fk(q0, lk)
|
| 826 |
+
X1 = np.linalg.inv(arms[s].fk(q1, "flange")) @ arms[s].fk(q1, lk)
|
| 827 |
+
drift = max(drift, float(np.abs(X0 - X1).max() * 1000))
|
| 828 |
+
out[lk][s] = X0
|
| 829 |
+
if drift > 1e-6:
|
| 830 |
+
raise RuntimeError("tool points move with joint angles (drift %.2e mm); "
|
| 831 |
+
"is the gripper not fixed to the flange in the URDF?" % drift)
|
| 832 |
+
self._tool_X = out
|
| 833 |
+
log.info("tool-aware pre-check enabled (FK=yourdfpy): %d rigid points %s, "
|
| 834 |
+
"threshold %.0f cm, joint-independent (drift %.1e mm)",
|
| 835 |
+
len(out), links, self.tool_min_dist * 100, drift)
|
| 836 |
+
except Exception as e: # noqa: BLE001
|
| 837 |
+
raise RuntimeError(
|
| 838 |
+
"failed to get tool geometry (%s): %s; the self-collision monitor ignores the grippers, so without "
|
| 839 |
+
"this check gripper-gripper contact is unprotected. Fix the URDF or set tool_min_dist=0 explicitly."
|
| 840 |
+
% (type(e).__name__, e))
|
| 841 |
+
|
| 842 |
+
# ------------------------------------------------------------------ startup self-tests
|
| 843 |
+
def _selftest_quat(self):
|
| 844 |
+
"""wxyz <-> xyzw round trip must be exact.
|
| 845 |
+
|
| 846 |
+
A wrong mapping looks like a bad hand-eye calibration, so test it explicitly. Uses a
|
| 847 |
+
measured pose, not identity (identity is a fixed point of many wrong mappings).
|
| 848 |
+
"""
|
| 849 |
+
worst = 0.0
|
| 850 |
+
for s in SIDES:
|
| 851 |
+
p = self._anchor_w[s]
|
| 852 |
+
back = _x2w(_w2x(p))
|
| 853 |
+
# q and -q are the same rotation; align signs before comparing
|
| 854 |
+
if float(np.dot(back[3:7], p[3:7])) < 0:
|
| 855 |
+
back[3:7] = -back[3:7]
|
| 856 |
+
worst = max(worst, float(np.abs(back - p).max()))
|
| 857 |
+
if worst > 1e-12:
|
| 858 |
+
raise RuntimeError("wxyz<->xyzw round trip not exact (max %.2e): conversion is wrong" % worst)
|
| 859 |
+
log.info("self-test quaternion round trip: exact (max diff %.1e, on measured anchor pose)", worst)
|
| 860 |
+
|
| 861 |
+
def _selftest_reachable(self):
|
| 862 |
+
"""End-to-end test of the pre-check chain (world -> arm base -> Model.reachable).
|
| 863 |
+
|
| 864 |
+
The current measured pose must be reachable and solve back to the current joints;
|
| 865 |
+
if not, the bridge or call is wrong. Also reports per-call latency.
|
| 866 |
+
"""
|
| 867 |
+
if self.ik_check == "off":
|
| 868 |
+
log.info("ik_check=off: skipping reachability pre-check")
|
| 869 |
+
return
|
| 870 |
+
t0 = time.perf_counter()
|
| 871 |
+
n_ok = 0
|
| 872 |
+
for s in SIDES:
|
| 873 |
+
q_now = np.asarray(self._st_q[s] if self._st_q[s] is not None
|
| 874 |
+
else self._anchor_q[s], float)
|
| 875 |
+
ok, _ = self._reachable(s, self._anchor_w[s], q_now)
|
| 876 |
+
if ok is None:
|
| 877 |
+
log.error("reachable() call failed; reachability pre-check disabled (other checks still active)")
|
| 878 |
+
return
|
| 879 |
+
if not ok:
|
| 880 |
+
raise RuntimeError(
|
| 881 |
+
"%s arm: even the current measured pose is unreachable; the bridge or call is wrong. "
|
| 882 |
+
"Refusing to run with a broken pre-check (it would truncate valid targets)" % s)
|
| 883 |
+
dq = float(np.abs(np.degrees(self._last_ik_q - q_now)).max())
|
| 884 |
+
n_ok += 1
|
| 885 |
+
log.info("self-test reachable [%-5s]: reachable, max joint diff to current %.3fdeg", s, dq)
|
| 886 |
+
ms = (time.perf_counter() - t0) / max(n_ok, 1) * 1000
|
| 887 |
+
log.info("self-test reachable: %.2f ms per call -> ~%.0f ms per 50-step dual-arm chunk "
|
| 888 |
+
"(chunk 1.7s, %.1f%%)", ms, ms * 100, ms * 100 / 1700 * 100)
|
| 889 |
+
|
| 890 |
+
# ------------------------------------------------------------------ gripper / camera
|
| 891 |
+
def _start_gripper(self):
|
| 892 |
+
from . import gripper_can
|
| 893 |
+
g = gripper_can.GripperPair(self.grip_cfg["calib"], kp=self.grip_cfg["kp"],
|
| 894 |
+
kd=self.grip_cfg["kd"],
|
| 895 |
+
lead_deg=self.grip_cfg["lead_deg"],
|
| 896 |
+
rate_hz=self.grip_cfg["rate_hz"], gain=1.0)
|
| 897 |
+
self._grip = g.open()
|
| 898 |
+
meas = {s: self._grip.measured_deg(s) for s in SIDES}
|
| 899 |
+
want = {s: float(np.clip(self.anchor_grip_deg[s], GRIP_MIN_DEG, GRIP_MAX_DEG))
|
| 900 |
+
for s in SIDES}
|
| 901 |
+
log.info("gripper bus open, measured opening left %.2fdeg right %.2fdeg (calib %s)",
|
| 902 |
+
meas["left"], meas["right"], os.path.basename(self.grip_cfg["calib"]))
|
| 903 |
+
log.info("anchor gripper opening left %.2fdeg right %.2fdeg",
|
| 904 |
+
want["left"], want["right"])
|
| 905 |
+
# Second floor: gripper_can.target_q applies max(deg, floor) and q >= q_closed+floor/dpr.
|
| 906 |
+
# floor defaults to 0; unless lowered too, the command lower bound is clamped back to 0 at the motor.
|
| 907 |
+
self._grip.set_floor_all({s: GRIP_CMD_MIN_DEG for s in SIDES})
|
| 908 |
+
log.info("gripper command floor set to %.2fdeg (to fit the -%.1fdeg offset; "
|
| 909 |
+
"otherwise target_q clamps it to 0)",
|
| 910 |
+
GRIP_CMD_MIN_DEG, GRIP_OFFSET_DEG)
|
| 911 |
+
if not self.dry_run:
|
| 912 |
+
# pin to the measured position before enabling; a large error at enable would snap the gripper
|
| 913 |
+
self._grip.set_all({s: float(np.clip(meas[s], GRIP_MIN_DEG, GRIP_MAX_DEG))
|
| 914 |
+
for s in SIDES})
|
| 915 |
+
self._grip.enable()
|
| 916 |
+
time.sleep(0.3)
|
| 917 |
+
# then ramp to the anchor opening over 1 s
|
| 918 |
+
n = 20
|
| 919 |
+
for i in range(1, n + 1):
|
| 920 |
+
a = i / n
|
| 921 |
+
self._grip.set_all({s: (1 - a) * meas[s] + a * want[s] for s in SIDES})
|
| 922 |
+
time.sleep(1.0 / n)
|
| 923 |
+
self._grip_ds = dict(want)
|
| 924 |
+
log.info("gripper at anchor opening, measured left %.2fdeg right %.2fdeg",
|
| 925 |
+
self._grip.measured_deg("left"), self._grip.measured_deg("right"))
|
| 926 |
+
log.info("gripper enabled (kp=%.0f kd=%.1f, command lead <= %.1fdeg => max torque ~%.1f Nm)",
|
| 927 |
+
self.grip_cfg["kp"], self.grip_cfg["kd"], self.grip_cfg["lead_deg"],
|
| 928 |
+
self.grip_cfg["kp"] * np.radians(self.grip_cfg["lead_deg"]))
|
| 929 |
+
else:
|
| 930 |
+
log.info("dry-run: gripper read-only, not enabled (doubles as wiring check)")
|
| 931 |
+
|
| 932 |
+
def _start_cameras(self):
|
| 933 |
+
from .insta_live import InstaDualCamera, kill_stale_cameras
|
| 934 |
+
if not all(CAM_SERIAL.values()):
|
| 935 |
+
raise RuntimeError("set INSTA360_LEFT_SN / INSTA360_RIGHT_SN for --live-camera")
|
| 936 |
+
# stale-process cleanup + discovery happen in InstaDualCamera.start()
|
| 937 |
+
last_err = None
|
| 938 |
+
for attempt in (1, 2, 3):
|
| 939 |
+
self._dual = InstaDualCamera(
|
| 940 |
+
serials={s: CAM_SERIAL[s] for s in SIDES},
|
| 941 |
+
halves={s: CAM_HALF[s] for s in SIDES},
|
| 942 |
+
out_size=CAM_OUT_SIZE, bitrate_kbps=self.cam_kbps,
|
| 943 |
+
pix_fmt="yuv420p" if self.cam_format == "yuv420p" else "rgb24")
|
| 944 |
+
try:
|
| 945 |
+
self._dual.start()
|
| 946 |
+
if self._dual.wait_ready(60.0):
|
| 947 |
+
break
|
| 948 |
+
last_err = "wait_ready timed out"
|
| 949 |
+
except Exception as e: # noqa: BLE001
|
| 950 |
+
last_err = "%s: %s" % (type(e).__name__, e)
|
| 951 |
+
# clean up fully before retrying; a half-dead process causes serial_not_found next time
|
| 952 |
+
log.warning("camera start attempt %d failed (%s), cleaning up and retrying ...", attempt, last_err)
|
| 953 |
+
try:
|
| 954 |
+
self._dual.stop()
|
| 955 |
+
except Exception: # noqa: BLE001
|
| 956 |
+
pass
|
| 957 |
+
self._dual = None
|
| 958 |
+
kill_stale_cameras(CAM_SERIAL.values(), "retry %d" % attempt)
|
| 959 |
+
if self._dual is None:
|
| 960 |
+
raise RuntimeError(
|
| 961 |
+
"wrist cameras failed to start 3 times (%s). Check: (1) camera USB mode set to Android control "
|
| 962 |
+
"(2) udev rule 99-insta360.rules (3) another process holding the device" % last_err)
|
| 963 |
+
log.info("wrist cameras ready: %s, half=%s, %dpx",
|
| 964 |
+
{s: CAM_SERIAL[s] for s in SIDES}, CAM_HALF, CAM_OUT_SIZE)
|
| 965 |
+
|
| 966 |
+
def _grab_images(self) -> "Dict[str, CameraFrame]":
|
| 967 |
+
import cv2
|
| 968 |
+
out: Dict[str, CameraFrame] = {}
|
| 969 |
+
now = time.time()
|
| 970 |
+
for s in SIDES:
|
| 971 |
+
rgb, stamp = self._dual.get_frame(s)
|
| 972 |
+
if rgb is None:
|
| 973 |
+
continue
|
| 974 |
+
if self.cam_format == "yuv420p":
|
| 975 |
+
h = rgb.shape[0] * 2 // 3
|
| 976 |
+
out[CAM_OBS_KEY[s]] = CameraFrame(
|
| 977 |
+
name=CAM_OBS_KEY[s], format="yuv420p", height=h, width=int(rgb.shape[1]),
|
| 978 |
+
data=rgb.tobytes(), stamp=float(stamp or now))
|
| 979 |
+
continue
|
| 980 |
+
ok, enc = cv2.imencode(".jpg", cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR),
|
| 981 |
+
[int(cv2.IMWRITE_JPEG_QUALITY), self.jpeg_quality])
|
| 982 |
+
if not ok:
|
| 983 |
+
continue
|
| 984 |
+
out[CAM_OBS_KEY[s]] = CameraFrame(
|
| 985 |
+
name=CAM_OBS_KEY[s], format="jpeg",
|
| 986 |
+
height=int(rgb.shape[0]), width=int(rgb.shape[1]),
|
| 987 |
+
data=enc.tobytes(), stamp=float(stamp or now))
|
| 988 |
+
return out
|
| 989 |
+
|
| 990 |
+
# ------------------------------------------------------------------ observation
|
| 991 |
+
def get_observation(self) -> Observation:
|
| 992 |
+
now = time.time()
|
| 993 |
+
with self._lock:
|
| 994 |
+
cur = {s: None if self._st_pose_w[s] is None else self._st_pose_w[s].copy()
|
| 995 |
+
for s in SIDES}
|
| 996 |
+
hist = list(self._hist)
|
| 997 |
+
prog = float(self._plan_progress)
|
| 998 |
+
st_age = now - self._st_t if self._st_t else np.inf
|
| 999 |
+
if any(cur[s] is None for s in SIDES):
|
| 1000 |
+
raise RuntimeError("no robot state yet (servo thread just started?); retry shortly")
|
| 1001 |
+
if st_age > 0.5 and now - self._stale_obs_warn > 2.0:
|
| 1002 |
+
# throttled: if the servo thread dies this would fire every observation
|
| 1003 |
+
self._stale_obs_warn = now
|
| 1004 |
+
log.warning("robot state is stale by %.2fs: servo thread dead or stuck (look above for "
|
| 1005 |
+
"Exception in thread)", st_age)
|
| 1006 |
+
|
| 1007 |
+
# [prev, cur] motion window: key to train/infer consistency.
|
| 1008 |
+
# By default look back 1 native frame of *executed trajectory progress*, not wall time.
|
| 1009 |
+
# With wall-clock lookback, a stationary arm yields near-zero motion (far below the
|
| 1010 |
+
# training distribution). Progress does not advance while chunks are rejected / holding
|
| 1011 |
+
# anchor / finished, so prev is always the last actually executed frame and motion has
|
| 1012 |
+
# training-like magnitude. Time mismatch is harmless: the model does not see time.
|
| 1013 |
+
# One native frame equals one chunk step only when upsample=1; dt*NATIVE_FPS handles the rest.
|
| 1014 |
+
lookback_f = max(1.0, round(self.pose_dt * NATIVE_FPS)) # seconds -> native frames
|
| 1015 |
+
prev, achieved = dict(cur), self.pose_dt
|
| 1016 |
+
grip_prev_raw = {s: None for s in SIDES}
|
| 1017 |
+
src, knots, sel = "cold", 0.0, None
|
| 1018 |
+
if self._prev_by_progress and hist and prog >= lookback_f:
|
| 1019 |
+
tgt = prog - lookback_f
|
| 1020 |
+
cand = min(hist, key=lambda e: abs(e[1] - tgt))
|
| 1021 |
+
if abs(cand[1] - tgt) <= PROGRESS_MAX_GAP_F:
|
| 1022 |
+
sel, src = cand, "progress"
|
| 1023 |
+
if sel is None:
|
| 1024 |
+
# fallback = wall-clock lookback, labeled (cold = not enough progress yet, wallclock = explicitly disabled)
|
| 1025 |
+
src = "cold" if self._prev_by_progress else "wallclock"
|
| 1026 |
+
if hist:
|
| 1027 |
+
tgt_t = now - self.pose_dt * self.play_scale
|
| 1028 |
+
sel = min(hist, key=lambda e: abs(e[0] - tgt_t))
|
| 1029 |
+
if sel is not None:
|
| 1030 |
+
prev = {s: sel[2][s].copy() for s in SIDES}
|
| 1031 |
+
grip_prev_raw = sel[3]
|
| 1032 |
+
achieved = max(now - sel[0], 1e-3)
|
| 1033 |
+
knots = round(prog - sel[1], 3)
|
| 1034 |
+
|
| 1035 |
+
eef, eef_prev, grip, grip_prev = {}, {}, {}, {}
|
| 1036 |
+
for s in SIDES:
|
| 1037 |
+
eef[s] = [float(x) for x in _w2x(cur[s])] # Flexiv wxyz -> protocol xyzw
|
| 1038 |
+
eef_prev[s] = [float(x) for x in _w2x(prev[s])]
|
| 1039 |
+
g = self._read_grip(s)
|
| 1040 |
+
grip[s] = g
|
| 1041 |
+
# Gripper prev = measured value at the selected frame; fall back to current if missing/NaN.
|
| 1042 |
+
# Clamp with the OBS bound to stay in distribution.
|
| 1043 |
+
gp = grip_prev_raw.get(s)
|
| 1044 |
+
grip_prev[s] = (float(np.clip(gp, GRIP_OBS_MIN_DEG, GRIP_MAX_DEG))
|
| 1045 |
+
if gp is not None and np.isfinite(gp) else g)
|
| 1046 |
+
self._warn_if_degenerate(cur, prev, src)
|
| 1047 |
+
self._seq += 1
|
| 1048 |
+
self._obs_pos[self._seq] = {s: cur[s][:3].copy() for s in SIDES}
|
| 1049 |
+
for k in [k for k in self._obs_pos if k < self._seq - 8]: # keep only the last few
|
| 1050 |
+
del self._obs_pos[k]
|
| 1051 |
+
obs = Observation(seq=self._seq, stamp=now,
|
| 1052 |
+
images=self._grab_images() if self._dual else {},
|
| 1053 |
+
eef=eef, gripper=grip, eef_prev=eef_prev,
|
| 1054 |
+
gripper_prev=grip_prev, pose_dt=achieved,
|
| 1055 |
+
extra={"prev": {"source": src, "knots": knots,
|
| 1056 |
+
"dt": round(achieved, 4)},
|
| 1057 |
+
"pose_dt_target": self.pose_dt,
|
| 1058 |
+
"plan_progress": round(prog, 3)})
|
| 1059 |
+
if self._rollout is not None:
|
| 1060 |
+
# exactly what the model gets: state + images (saved in background as obs/<seq>_<key>.jpg)
|
| 1061 |
+
self._rollout.event({"event": "obs", "seq": obs.seq, "eef": eef, "eef_prev": eef_prev,
|
| 1062 |
+
"gripper": grip, "gripper_prev": grip_prev,
|
| 1063 |
+
"pose_dt": achieved, "prev": obs.extra["prev"],
|
| 1064 |
+
"plan_progress": round(prog, 3),
|
| 1065 |
+
"img_stamp": {k: f.stamp for k, f in obs.images.items()}})
|
| 1066 |
+
self._rollout.obs_images(obs.seq, obs.images)
|
| 1067 |
+
return obs
|
| 1068 |
+
|
| 1069 |
+
def _warn_if_degenerate(self, cur, prev, src) -> None:
|
| 1070 |
+
"""Warn when observed motion falls below the training p10 (TRAIN_P10_*). Warning only, throttled 2s."""
|
| 1071 |
+
from scipy.spatial.transform import Rotation as Rot
|
| 1072 |
+
bad = []
|
| 1073 |
+
for s in SIDES:
|
| 1074 |
+
mm = float(np.linalg.norm(cur[s][:3] - prev[s][:3]) * 1000)
|
| 1075 |
+
r0 = Rot.from_quat(cur[s][[4, 5, 6, 3]]) # pose7 wxyz -> xyzw
|
| 1076 |
+
r1 = Rot.from_quat(prev[s][[4, 5, 6, 3]])
|
| 1077 |
+
dg = float(np.degrees((r1.inv() * r0).magnitude()))
|
| 1078 |
+
if mm < TRAIN_P10_MM or dg < TRAIN_P10_DEG:
|
| 1079 |
+
bad.append("%s %.3fmm/%.4fdeg" % (s[0].upper(), mm, dg))
|
| 1080 |
+
if not bad:
|
| 1081 |
+
return
|
| 1082 |
+
t = time.time()
|
| 1083 |
+
if t - self._degen_warn > 2.0:
|
| 1084 |
+
self._degen_warn = t
|
| 1085 |
+
log.warning("low observed motion %s (training per-frame p10=%.3fmm/%.3fdeg median=1.42mm/0.38deg) "
|
| 1086 |
+
"prev source=%s; the model's motion cue may be useless",
|
| 1087 |
+
" ".join(bad), TRAIN_P10_MM, TRAIN_P10_DEG, src)
|
| 1088 |
+
|
| 1089 |
+
def _grip_meas_raw(self, side: str):
|
| 1090 |
+
"""Measured gripper opening (unclamped) for history; reads a cached field, cheap."""
|
| 1091 |
+
if self._grip is None:
|
| 1092 |
+
return None
|
| 1093 |
+
try:
|
| 1094 |
+
v = float(self._grip.measured_deg(side))
|
| 1095 |
+
except Exception: # noqa: BLE001
|
| 1096 |
+
return None
|
| 1097 |
+
return v if np.isfinite(v) else None
|
| 1098 |
+
|
| 1099 |
+
def _read_grip(self, side: str) -> float:
|
| 1100 |
+
"""Measured gripper opening (dataset scale: 0 = closed, 90 = fully open)."""
|
| 1101 |
+
if self._grip is None:
|
| 1102 |
+
return float(self._grip_ds[side])
|
| 1103 |
+
try:
|
| 1104 |
+
v = float(self._grip.measured_deg(side))
|
| 1105 |
+
except Exception: # noqa: BLE001
|
| 1106 |
+
return float(self._grip_ds[side])
|
| 1107 |
+
# Clamp to the training range before reporting, using the OBS bound (not the command bound),
|
| 1108 |
+
# so the model never sees out-of-distribution values (see constants above).
|
| 1109 |
+
v = float(np.clip(v, GRIP_OBS_MIN_DEG, GRIP_MAX_DEG))
|
| 1110 |
+
self._grip_ds[side] = v
|
| 1111 |
+
return v
|
| 1112 |
+
|
| 1113 |
+
# ------------------------------------------------------------------ action
|
| 1114 |
+
def apply_action(self, action: Action) -> None:
|
| 1115 |
+
lt = self._load_lt()
|
| 1116 |
+
traj = {s: np.asarray(action.eef_traj.get(s, []), float) for s in SIDES}
|
| 1117 |
+
grips = {s: np.asarray(action.gripper_traj.get(s, []), float) for s in SIDES}
|
| 1118 |
+
M = max(len(traj[s]) for s in SIDES)
|
| 1119 |
+
if M == 0:
|
| 1120 |
+
log.warning("seq=%d empty action chunk", action.seq)
|
| 1121 |
+
return
|
| 1122 |
+
self._health["chunks"] += 1
|
| 1123 |
+
|
| 1124 |
+
# ---- protocol (xyzw) -> Flexiv (wxyz), rejecting invalid quaternions ----
|
| 1125 |
+
pose_w = np.zeros((M, 2, 7))
|
| 1126 |
+
for h, s in enumerate(SIDES):
|
| 1127 |
+
t = traj[s]
|
| 1128 |
+
for i in range(M):
|
| 1129 |
+
p = t[min(i, len(t) - 1)]
|
| 1130 |
+
if not np.all(np.isfinite(p)):
|
| 1131 |
+
log.error("seq=%d %s arm step %d has non-finite values -> chunk rejected: %s",
|
| 1132 |
+
action.seq, s, i, p.tolist())
|
| 1133 |
+
self._health["rejected"] += 1
|
| 1134 |
+
self._trace_write({"event": "chunk", "seq": action.seq, "n_model": M,
|
| 1135 |
+
"keep": 0, "status": "rejected",
|
| 1136 |
+
"why": "%s arm step %d non-finite" % (s, i),
|
| 1137 |
+
"policy": (action.extra or {}).get("policy")})
|
| 1138 |
+
return
|
| 1139 |
+
pose_w[i, h] = _x2w(p)
|
| 1140 |
+
|
| 1141 |
+
# ---- reach scaling: origin = measured position at this chunk's observation ----
|
| 1142 |
+
o = self._obs_pos.pop(action.seq, None)
|
| 1143 |
+
for h, s in enumerate(SIDES):
|
| 1144 |
+
k = REACH_SCALE[s]
|
| 1145 |
+
if k != 1.0 and o is not None:
|
| 1146 |
+
pose_w[:, h, :3] = o[s] + k * (pose_w[:, h, :3] - o[s])
|
| 1147 |
+
|
| 1148 |
+
grip_t = np.zeros((M, 2))
|
| 1149 |
+
for h, s in enumerate(SIDES):
|
| 1150 |
+
g = grips[s]
|
| 1151 |
+
for i in range(M):
|
| 1152 |
+
raw = (float(g[min(i, len(g) - 1)]) if len(g)
|
| 1153 |
+
else self._grip_ds[s] + GRIP_OFFSET_DEG)
|
| 1154 |
+
# track the raw model output (before offset)
|
| 1155 |
+
self._grip_seen["lo"][s] = min(self._grip_seen["lo"][s], raw)
|
| 1156 |
+
self._grip_seen["hi"][s] = max(self._grip_seen["hi"][s], raw)
|
| 1157 |
+
grip_t[i, h] = float(np.clip(raw - GRIP_OFFSET_DEG,
|
| 1158 |
+
GRIP_CMD_MIN_DEG, GRIP_MAX_DEG))
|
| 1159 |
+
|
| 1160 |
+
# ---- steps per chunk: keep the first N model steps (first chunk separate), drop the rest ----
|
| 1161 |
+
n_raw = M
|
| 1162 |
+
lim = self.first_steps if self._health["chunks"] == 1 else self.steps
|
| 1163 |
+
if lim and M > lim:
|
| 1164 |
+
pose_w, grip_t, M = pose_w[:lim], grip_t[:lim], lim
|
| 1165 |
+
|
| 1166 |
+
self._ik_trace = None
|
| 1167 |
+
keep, why = self._precheck(action.seq, pose_w, lt)
|
| 1168 |
+
# model output before truncation (world-frame flange poses, wxyz)
|
| 1169 |
+
trace = {"event": "chunk", "seq": action.seq, "n_raw": n_raw, "n_model": M,
|
| 1170 |
+
"keep": int(max(keep, 0)),
|
| 1171 |
+
"why": why, "dt": float(action.dt or 1.0 / 30.0),
|
| 1172 |
+
"play_scale": self.play_scale,
|
| 1173 |
+
"policy": (action.extra or {}).get("policy"),
|
| 1174 |
+
"reach_scale": REACH_SCALE, # model is already reach-scaled (what is sent)
|
| 1175 |
+
"model": {s: np.round(pose_w[:, IDX[s]], 5).tolist() for s in SIDES},
|
| 1176 |
+
"ik": self._ik_trace}
|
| 1177 |
+
if keep <= 0:
|
| 1178 |
+
self._health["rejected"] += 1
|
| 1179 |
+
log.warning("seq=%d pre-check failed -> holding until next inference: %s", action.seq, why)
|
| 1180 |
+
self._trace_write({**trace, "status": "rejected"})
|
| 1181 |
+
return
|
| 1182 |
+
if keep < M:
|
| 1183 |
+
self._health["truncated"] += 1
|
| 1184 |
+
log.warning("seq=%d pre-check truncated: keeping first %d/%d steps (%s)", action.seq, keep, M, why)
|
| 1185 |
+
pose_w, grip_t = pose_w[:keep], grip_t[:keep]
|
| 1186 |
+
M = keep
|
| 1187 |
+
|
| 1188 |
+
dt = float(action.dt or 1.0 / 30.0)
|
| 1189 |
+
twist = self._twists(pose_w, dt) if self.feedforward else np.zeros((M, 2, 6))
|
| 1190 |
+
|
| 1191 |
+
# ---- chunk seam: start the new chunk at the point closest to the last command ----
|
| 1192 |
+
# The policy anchors a chunk at the pose at observation time. In sync mode the seam is ~0;
|
| 1193 |
+
# in async mode the anchor is stale and starting at step 0 would jump backwards.
|
| 1194 |
+
# No crossfade on top of k0; the residual seam goes straight to the arm, so it is logged.
|
| 1195 |
+
# NOTE: k0 is picked by nearest position, not time; it can pick wrong when the path revisits
|
| 1196 |
+
# a position, and has no bound beyond half a chunk. Better: k0 = latency/dt, position for refinement.
|
| 1197 |
+
now_pc = time.perf_counter()
|
| 1198 |
+
with self._lock:
|
| 1199 |
+
last = None if self._last_cmd_w is None else self._last_cmd_w.copy()
|
| 1200 |
+
k0, seam_mm = 0, None
|
| 1201 |
+
if last is not None and M > 1:
|
| 1202 |
+
half = max(1, M // 2) # search only the first half to avoid matching the far tail
|
| 1203 |
+
d = np.linalg.norm(pose_w[:half, :, :3] - last[None, :, :3], axis=(1, 2))
|
| 1204 |
+
k0 = int(np.argmin(d))
|
| 1205 |
+
# seam residual (per arm, mm): position jump the arm takes at the switch
|
| 1206 |
+
seam_mm = np.linalg.norm(pose_w[k0, :, :3] - last[:, :3], axis=1) * 1000.0
|
| 1207 |
+
with self._lock:
|
| 1208 |
+
self._buf = _Buf(pose_w=pose_w, twist=twist, grip=grip_t, dt=dt,
|
| 1209 |
+
start=now_pc - k0 * dt * self.play_scale,
|
| 1210 |
+
seq=action.seq,
|
| 1211 |
+
truncated_from=keep,
|
| 1212 |
+
meta=dict(action.extra or {}))
|
| 1213 |
+
# new chunk = rebuild baseline: first send records the knot without counting, so the k0 skip is not counted as progress
|
| 1214 |
+
self._plan_knot_last = None
|
| 1215 |
+
log.info("seq=%d chunk %d steps%s dt=%.4f x%.2f slower (plays %.2fs) start k0=%d seam %s%s",
|
| 1216 |
+
action.seq, M, "" if n_raw == M else " (model gave %d, took first %d)" % (n_raw, M),
|
| 1217 |
+
dt, self.play_scale,
|
| 1218 |
+
(M - 1) * dt * self.play_scale, k0,
|
| 1219 |
+
"-" if seam_mm is None else ("left %.2f right %.2f mm" % tuple(seam_mm)),
|
| 1220 |
+
" [dry-run, not sent]" if self.dry_run else "")
|
| 1221 |
+
self._trace_write({**trace, "status": "truncated" if keep < trace["n_model"] else "ok",
|
| 1222 |
+
"k0": k0,
|
| 1223 |
+
"seam_mm": None if seam_mm is None else np.round(seam_mm, 2).tolist()})
|
| 1224 |
+
|
| 1225 |
+
def _twists(self, pose_w, dt):
|
| 1226 |
+
"""Feedforward twist [v(3), w(3)] from a pose chunk (central differences, one-sided at ends)."""
|
| 1227 |
+
from scipy.spatial.transform import Rotation as Rot
|
| 1228 |
+
M = pose_w.shape[0]
|
| 1229 |
+
tw = np.zeros((M, 2, 6))
|
| 1230 |
+
if M < 2 or dt <= 0:
|
| 1231 |
+
return tw
|
| 1232 |
+
for h in range(2):
|
| 1233 |
+
p = pose_w[:, h, :3]
|
| 1234 |
+
q = pose_w[:, h, 3:7][:, [1, 2, 3, 0]] # wxyz -> xyzw (scipy)
|
| 1235 |
+
R = Rot.from_quat(q)
|
| 1236 |
+
for i in range(M):
|
| 1237 |
+
a, b = max(i - 1, 0), min(i + 1, M - 1)
|
| 1238 |
+
span = (b - a) * dt
|
| 1239 |
+
if span <= 0:
|
| 1240 |
+
continue
|
| 1241 |
+
tw[i, h, :3] = (p[b] - p[a]) / span
|
| 1242 |
+
tw[i, h, 3:] = (R[b] * R[a].inv()).as_rotvec() / span
|
| 1243 |
+
# The last step is where the arm must stop (sync mode waits for inference), so its velocity
|
| 1244 |
+
# must be 0; a one-sided difference here makes position and feedforward fight -> oscillation.
|
| 1245 |
+
tw[-1] = 0.0
|
| 1246 |
+
return tw / self.play_scale # slowed playback scales velocity down; scale feedforward too
|
| 1247 |
+
|
| 1248 |
+
@staticmethod
|
| 1249 |
+
def _ff_twist(buf, phase):
|
| 1250 |
+
"""Feedforward twist for this servo cycle: linearly interpolated like position; 0 once the chunk ends."""
|
| 1251 |
+
n = len(buf.twist)
|
| 1252 |
+
if phase >= n - 1:
|
| 1253 |
+
return np.zeros((2, 6))
|
| 1254 |
+
i = int(np.clip(phase, 0, n - 1))
|
| 1255 |
+
a = float(np.clip(phase - i, 0.0, 1.0))
|
| 1256 |
+
return (1 - a) * buf.twist[i] + a * buf.twist[min(i + 1, n - 1)]
|
| 1257 |
+
|
| 1258 |
+
def _precheck(self, seq, pose_w, lt):
|
| 1259 |
+
"""Check the whole chunk before sending. Returns (steps to execute, reason).
|
| 1260 |
+
|
| 1261 |
+
Independent failure modes, checked and reported separately:
|
| 1262 |
+
(1) step jump - occasional model outliers; large jumps leave the gap unsupervised
|
| 1263 |
+
(2) reachability - flexivrdk.Model.reachable; do not send what the robot's IK rejects
|
| 1264 |
+
(3) tool distance - the self-collision monitor cannot see the UMI grippers
|
| 1265 |
+
The earliest cut point wins.
|
| 1266 |
+
"""
|
| 1267 |
+
M = pose_w.shape[0]
|
| 1268 |
+
first_bad, reasons = M, []
|
| 1269 |
+
|
| 1270 |
+
def cut(i, why):
|
| 1271 |
+
nonlocal first_bad
|
| 1272 |
+
if i < first_bad:
|
| 1273 |
+
first_bad = i
|
| 1274 |
+
reasons.append(why)
|
| 1275 |
+
|
| 1276 |
+
# (1) step jump
|
| 1277 |
+
if M > 1:
|
| 1278 |
+
step = np.linalg.norm(np.diff(pose_w[:, :, :3], axis=0), axis=2) * 1000 # (M-1,2)
|
| 1279 |
+
bad = np.where(step.max(axis=1) > self.max_step_mm)[0]
|
| 1280 |
+
if len(bad):
|
| 1281 |
+
cut(int(bad[0]) + 1, "step %d jump %.0f mm > %.0f"
|
| 1282 |
+
% (bad[0] + 1, step[bad[0]].max(), self.max_step_mm))
|
| 1283 |
+
|
| 1284 |
+
# (2) reachability (robot's own IK), sampled rather than per step:
|
| 1285 |
+
# `Model.reachable` takes ~6.4 ms ([Blocking], goes through the controller); checking all 50
|
| 1286 |
+
# dual-arm steps would take ~38% of a chunk and may contend with the 100 Hz command stream.
|
| 1287 |
+
# So check ik_max_calls points, always including first and last (the last is farthest).
|
| 1288 |
+
# Unsampled steps have no reachability result; other checks do not replace it.
|
| 1289 |
+
if self.ik_check != "off":
|
| 1290 |
+
n_bad, first_ik, last_good = 0, None, 0
|
| 1291 |
+
seed = {s: np.asarray(self._st_q[s] if self._st_q[s] is not None
|
| 1292 |
+
else self._anchor_q[s], float) for s in SIDES}
|
| 1293 |
+
per_arm = max(2, self.ik_max_calls // 2)
|
| 1294 |
+
idxs = sorted(set(np.linspace(0, M - 1, min(per_arm, M)).astype(int).tolist()))
|
| 1295 |
+
t_ik = time.perf_counter()
|
| 1296 |
+
ik_tr = {"idx": idxs, **{s: {"ok": [], "q": []} for s in SIDES}}
|
| 1297 |
+
for i in idxs:
|
| 1298 |
+
step_ok = True
|
| 1299 |
+
for s in SIDES:
|
| 1300 |
+
ok, q_sol = self._reachable(s, pose_w[i, IDX[s]], seed[s])
|
| 1301 |
+
ik_tr[s]["ok"].append(ok)
|
| 1302 |
+
ik_tr[s]["q"].append(None if not ok else np.round(q_sol, 5).tolist())
|
| 1303 |
+
if ok is None: # call failed; not treated as unreachable
|
| 1304 |
+
continue
|
| 1305 |
+
if not ok:
|
| 1306 |
+
n_bad += 1
|
| 1307 |
+
step_ok = False
|
| 1308 |
+
if first_ik is None:
|
| 1309 |
+
first_ik = i
|
| 1310 |
+
elif self._last_ik_q is not None:
|
| 1311 |
+
seed[s] = self._last_ik_q # chained seed: keeps solutions continuous, no branch jumps
|
| 1312 |
+
if step_ok:
|
| 1313 |
+
last_good = i
|
| 1314 |
+
ik_ms = (time.perf_counter() - t_ik) * 1000
|
| 1315 |
+
self._ik_trace = ik_tr
|
| 1316 |
+
if n_bad:
|
| 1317 |
+
self._health["ik_bad"] += n_bad
|
| 1318 |
+
# conservative: cut at the last checked-and-passed point; unsampled steps are not assumed good
|
| 1319 |
+
msg = ("IK: sampled %d points (of %d steps), %d arm-steps unreachable, first at step %d; "
|
| 1320 |
+
"cut at last checked step %d" % (len(idxs), M, n_bad, first_ik, last_good))
|
| 1321 |
+
if self.ik_check == "warn":
|
| 1322 |
+
log.warning("seq=%d %s (ik_check=warn, sending anyway)", seq, msg)
|
| 1323 |
+
elif self.ik_check == "abort":
|
| 1324 |
+
cut(0, msg)
|
| 1325 |
+
else:
|
| 1326 |
+
cut(int(last_good), msg)
|
| 1327 |
+
elif ik_ms > 250:
|
| 1328 |
+
log.warning("reachability pre-check took %.0f ms (%d points); slow, use --ik-check off to skip",
|
| 1329 |
+
ik_ms, len(idxs))
|
| 1330 |
+
|
| 1331 |
+
# (3) tool-aware arm distance
|
| 1332 |
+
if self._tool_X is not None:
|
| 1333 |
+
abs_p = {s: pose_w[:, IDX[s], :] for s in SIDES}
|
| 1334 |
+
try:
|
| 1335 |
+
# returns (per-frame min distance [M], global min, closest frame, (left link, right link))
|
| 1336 |
+
per_frame, dmin, f_min, pair_lk = lt.pair_distance_tools(abs_p, self._tool_X)
|
| 1337 |
+
bad = np.where(np.asarray(per_frame) < self.tool_min_dist)[0]
|
| 1338 |
+
if len(bad):
|
| 1339 |
+
cut(int(bad[0]),
|
| 1340 |
+
"with gripper geometry: step %d arm distance %.3f m < %.3f (closest pair %s<->%s, frame %d)"
|
| 1341 |
+
% (bad[0], float(per_frame[bad[0]]), self.tool_min_dist,
|
| 1342 |
+
pair_lk[0], pair_lk[1], f_min))
|
| 1343 |
+
except Exception as e: # noqa: BLE001
|
| 1344 |
+
log.error("tool-aware distance pre-check failed (%s): %s; treating chunk as unsafe", type(e).__name__, e)
|
| 1345 |
+
cut(0, "tool-aware distance pre-check failed")
|
| 1346 |
+
|
| 1347 |
+
return first_bad, "; ".join(reasons) if reasons else "all passed"
|
| 1348 |
+
|
| 1349 |
+
def _reachable(self, side, pose_w7, seed_q):
|
| 1350 |
+
"""Flexiv reachable(). Input: world-frame (wxyz) flange pose. Returns (reachable?, joints rad or None).
|
| 1351 |
+
|
| 1352 |
+
Model is built from the single-arm Robot and takes arm-base poses; map via the measured bridge.
|
| 1353 |
+
The residual cannot be recomputed from the solution (the T() Python binding is broken:
|
| 1354 |
+
Unregistered type), so only reachability is reported; joints are recorded in the trace.
|
| 1355 |
+
"""
|
| 1356 |
+
lt = self._lt
|
| 1357 |
+
try:
|
| 1358 |
+
T_b = np.linalg.inv(self._bridge[side]) @ lt.pose7_to_T(pose_w7)
|
| 1359 |
+
ok, sol = self._models[side].reachable(
|
| 1360 |
+
[float(v) for v in lt.T_to_pose7(T_b)],
|
| 1361 |
+
[float(v) for v in np.asarray(seed_q, float)], False)
|
| 1362 |
+
if ok:
|
| 1363 |
+
self._last_ik_q = np.asarray(sol, float)
|
| 1364 |
+
return bool(ok), (self._last_ik_q if ok else None)
|
| 1365 |
+
except Exception as e: # noqa: BLE001
|
| 1366 |
+
if not getattr(self, "_ik_warned", False):
|
| 1367 |
+
self._ik_warned = True
|
| 1368 |
+
log.warning("reachable() call failed (%s: %s); not reporting again. "
|
| 1369 |
+
"Reachability pre-check disabled, other checks still active", type(e).__name__, e)
|
| 1370 |
+
return None, None
|
| 1371 |
+
|
| 1372 |
+
def needs_refill(self, fraction: float) -> bool:
|
| 1373 |
+
with self._lock:
|
| 1374 |
+
buf = self._buf
|
| 1375 |
+
if buf is None or buf.seq < 0:
|
| 1376 |
+
return True # still at anchor, need the first chunk now
|
| 1377 |
+
n = len(buf.pose_w)
|
| 1378 |
+
if n <= 1:
|
| 1379 |
+
return True
|
| 1380 |
+
elapsed = time.perf_counter() - buf.start
|
| 1381 |
+
return elapsed >= fraction * (n - 1) * buf.dt * self.play_scale
|
| 1382 |
+
|
| 1383 |
+
# ------------------------------------------------------------------ servo
|
| 1384 |
+
def _servo_loop(self):
|
| 1385 |
+
from scipy.spatial.transform import Rotation as Rot, Slerp
|
| 1386 |
+
lt = self._lt
|
| 1387 |
+
period = 1.0 / self.servo_rate_hz
|
| 1388 |
+
zero6 = [0.0] * 6
|
| 1389 |
+
last_idx, last_log = -1, 0.0
|
| 1390 |
+
last_seq, hold_seq = None, None
|
| 1391 |
+
while not self._stop_ev.is_set():
|
| 1392 |
+
t_cycle = time.perf_counter()
|
| 1393 |
+
with self._lock:
|
| 1394 |
+
buf = self._buf
|
| 1395 |
+
if buf is None:
|
| 1396 |
+
time.sleep(period)
|
| 1397 |
+
continue
|
| 1398 |
+
|
| 1399 |
+
n = len(buf.pose_w)
|
| 1400 |
+
slow_dt = buf.dt * self.play_scale
|
| 1401 |
+
phase = ((time.perf_counter() - buf.start) / slow_dt) if slow_dt > 0 else 0.0
|
| 1402 |
+
i = int(np.clip(phase, 0, n - 1))
|
| 1403 |
+
j = min(i + 1, n - 1)
|
| 1404 |
+
a = float(np.clip(phase - i, 0.0, 1.0))
|
| 1405 |
+
|
| 1406 |
+
# ---- interpolation: linear position + Slerp orientation ----
|
| 1407 |
+
# Not zero-order hold: low-rate step commands through a stiff loop cause visible jitter.
|
| 1408 |
+
cmd = np.zeros((2, 7))
|
| 1409 |
+
for h in range(2):
|
| 1410 |
+
p0, p1 = buf.pose_w[i, h], buf.pose_w[j, h]
|
| 1411 |
+
pos = (1 - a) * p0[:3] + a * p1[:3]
|
| 1412 |
+
if i == j or a <= 0:
|
| 1413 |
+
quat_w = p0[3:7]
|
| 1414 |
+
else:
|
| 1415 |
+
R01 = Rot.from_quat(np.stack([p0[3:7][[1, 2, 3, 0]],
|
| 1416 |
+
p1[3:7][[1, 2, 3, 0]]]))
|
| 1417 |
+
Rm = Slerp([0.0, 1.0], R01)(a).as_matrix()
|
| 1418 |
+
quat_w = lt.R_to_quat_wxyz(Rm)
|
| 1419 |
+
cmd[h] = np.concatenate([pos, quat_w])
|
| 1420 |
+
|
| 1421 |
+
tw = self._ff_twist(buf, phase) if self.feedforward else np.zeros((2, 6))
|
| 1422 |
+
|
| 1423 |
+
# ---- send + read state ----
|
| 1424 |
+
st = None
|
| 1425 |
+
sent = True # dry-run counts as accepted (simulated successful send)
|
| 1426 |
+
if not self.dry_run:
|
| 1427 |
+
try:
|
| 1428 |
+
self._pair.SendCartesianMotionForce(
|
| 1429 |
+
(cmd[0].tolist(), cmd[1].tolist()),
|
| 1430 |
+
velocities=(tw[0].tolist(), tw[1].tolist()),
|
| 1431 |
+
**self.vel_caps)
|
| 1432 |
+
except Exception as e: # noqa: BLE001
|
| 1433 |
+
sent = False
|
| 1434 |
+
log.error("SendCartesianMotionForce failed: %s", e)
|
| 1435 |
+
|
| 1436 |
+
# ---- advance trajectory progress (native frames) ----
|
| 1437 |
+
# Counts only successful sends; anchor hold (seq<0) and failed sends do not count (and
|
| 1438 |
+
# rebuild the baseline). After a chunk ends phase is clamped, so progress stops.
|
| 1439 |
+
# This is what lets prev skip pauses; think before changing it.
|
| 1440 |
+
with self._lock:
|
| 1441 |
+
if buf.seq < 0 or not sent:
|
| 1442 |
+
self._plan_knot_last = None
|
| 1443 |
+
else:
|
| 1444 |
+
knot = float(np.clip(phase, 0.0, n - 1)) * buf.dt * NATIVE_FPS
|
| 1445 |
+
if self._plan_knot_last is not None:
|
| 1446 |
+
self._plan_progress += max(0.0, knot - self._plan_knot_last)
|
| 1447 |
+
self._plan_knot_last = knot
|
| 1448 |
+
try:
|
| 1449 |
+
st = self._sd(self._pair.states())
|
| 1450 |
+
except Exception as e: # noqa: BLE001
|
| 1451 |
+
log.error("reading state failed: %s", e)
|
| 1452 |
+
|
| 1453 |
+
if st is not None:
|
| 1454 |
+
pose_w = {s: lt.normalize_pose7(np.asarray(st[s].tcp_pose, float))
|
| 1455 |
+
for s in SIDES}
|
| 1456 |
+
q = {s: np.asarray(st[s].q, float) for s in SIDES}
|
| 1457 |
+
with self._lock:
|
| 1458 |
+
for s in SIDES:
|
| 1459 |
+
self._st_pose_w[s] = pose_w[s]
|
| 1460 |
+
self._st_q[s] = q[s]
|
| 1461 |
+
self._st_t = time.time()
|
| 1462 |
+
self._last_cmd_w = cmd.copy()
|
| 1463 |
+
self._hist.append((time.time(), float(self._plan_progress),
|
| 1464 |
+
{s: pose_w[s].copy() for s in SIDES},
|
| 1465 |
+
{s: self._grip_meas_raw(s) for s in SIDES}))
|
| 1466 |
+
if len(self._hist) > 1200:
|
| 1467 |
+
del self._hist[:600]
|
| 1468 |
+
|
| 1469 |
+
reason, pair_d = self._guard(pose_w)
|
| 1470 |
+
self._health["min_pair_m"] = min(self._health["min_pair_m"], pair_d)
|
| 1471 |
+
if reason is not None:
|
| 1472 |
+
self._health["abort"] = reason
|
| 1473 |
+
log.error("per-cycle guard abort: %s", reason)
|
| 1474 |
+
self._trace_write({"event": "abort", "seq": buf.seq, "idx": i,
|
| 1475 |
+
"reason": reason})
|
| 1476 |
+
self._emergency_stop()
|
| 1477 |
+
return
|
| 1478 |
+
|
| 1479 |
+
# One row per servo cycle (100Hz, so tracking-error peaks are not missed). phase column:
|
| 1480 |
+
# run = chunk playing; wait = chunk done, command held at last point;
|
| 1481 |
+
# hold = one extra row HOLD_ROW_S after the end; its act = final settled pose
|
| 1482 |
+
hold = (buf.seq >= 0 and hold_seq != buf.seq
|
| 1483 |
+
and (phase - (n - 1)) * slow_dt >= HOLD_ROW_S)
|
| 1484 |
+
if self._rec_w is not None:
|
| 1485 |
+
if hold:
|
| 1486 |
+
hold_seq = buf.seq
|
| 1487 |
+
tag = ("hold" if hold else "wait" if (buf.seq >= 0 and phase > n - 1)
|
| 1488 |
+
else buf.meta.get("phase", "run"))
|
| 1489 |
+
row = ["%.4f" % time.time(), buf.seq, i, tag]
|
| 1490 |
+
for h, s in enumerate(SIDES):
|
| 1491 |
+
row += ["%.5f" % v for v in cmd[h]]
|
| 1492 |
+
row += ["%.5f" % v for v in pose_w[s][:3]]
|
| 1493 |
+
row += ["%.2f" % buf.grip[i, h], "%.2f" % self._grip_ds[s]]
|
| 1494 |
+
row += ["%.4f" % pair_d]
|
| 1495 |
+
for s in SIDES:
|
| 1496 |
+
row += ["%.5f" % v for v in pose_w[s][3:7]]
|
| 1497 |
+
for s in SIDES:
|
| 1498 |
+
row += ["%.5f" % v for v in q[s]]
|
| 1499 |
+
row += ["%.3f" % float(np.clip(phase, 0.0, n - 1))]
|
| 1500 |
+
for s in SIDES:
|
| 1501 |
+
for attr in ("ext_wrench_in_world", "ext_wrench_in_tcp"):
|
| 1502 |
+
ext = getattr(st[s], attr, None)
|
| 1503 |
+
row += (["%.2f" % v for v in ext]
|
| 1504 |
+
if ext is not None and len(ext) == 6 else ["nan"] * 6)
|
| 1505 |
+
self._rec_w.writerow(row)
|
| 1506 |
+
if self._rollout is not None:
|
| 1507 |
+
self._rollout_servo(st, pose_w, q, cmd, buf, i, n, phase, hold, sent,
|
| 1508 |
+
pair_d, t_cycle)
|
| 1509 |
+
|
| 1510 |
+
now = time.time()
|
| 1511 |
+
if now - last_log > 1.0:
|
| 1512 |
+
last_log = now
|
| 1513 |
+
log.info(" seq=%d %d/%d arm dist %.3f m%s",
|
| 1514 |
+
buf.seq, i, n, pair_d,
|
| 1515 |
+
(" gripper " + self._grip.status_line()) if self._grip else "")
|
| 1516 |
+
|
| 1517 |
+
# ---- gripper: pass model output through ----
|
| 1518 |
+
# Only the mechanical-travel clamp (done in apply_action); no grasp logic here.
|
| 1519 |
+
if self._grip is not None and not self.dry_run:
|
| 1520 |
+
try:
|
| 1521 |
+
self._grip.set_all({s: float(buf.grip[i, IDX[s]]) for s in SIDES})
|
| 1522 |
+
except Exception as e: # noqa: BLE001
|
| 1523 |
+
log.error("gripper command failed: %s", e)
|
| 1524 |
+
|
| 1525 |
+
last_idx, last_seq = i, buf.seq
|
| 1526 |
+
# Chunk expired: hold the last command, do not stop. Holding a reached pose in Cartesian
|
| 1527 |
+
# mode is static; Stop() would change mode and require re-entering + re-setting impedance.
|
| 1528 |
+
over_s = (phase - (n - 1)) * slow_dt
|
| 1529 |
+
if buf.seq >= 0 and over_s > self.max_stale_s:
|
| 1530 |
+
t_now = time.time()
|
| 1531 |
+
if t_now - getattr(self, "_stale_warn", 0.0) > 2.0:
|
| 1532 |
+
self._stale_warn = t_now
|
| 1533 |
+
log.warning("chunk seq=%d finished %.1fs ago, no new chunk; holding last pose. "
|
| 1534 |
+
"Is the inference server down?", buf.seq, over_s)
|
| 1535 |
+
time.sleep(max(0.0, period - (time.perf_counter() - t_cycle)))
|
| 1536 |
+
|
| 1537 |
+
def _guard(self, pose_w):
|
| 1538 |
+
"""Per-cycle safety check. Returns (abort reason or None, arm distance m)."""
|
| 1539 |
+
act = {s: pose_w[s][:3] for s in SIDES}
|
| 1540 |
+
pair_d = float(np.linalg.norm(act["left"] - act["right"]))
|
| 1541 |
+
if self.dry_run:
|
| 1542 |
+
return None, pair_d
|
| 1543 |
+
try:
|
| 1544 |
+
if self._pair.fault():
|
| 1545 |
+
w = self._pair.which_fault()
|
| 1546 |
+
return "fault (left=%s right=%s)" % (w[0], w[1]), pair_d
|
| 1547 |
+
m = self._pair.mode()
|
| 1548 |
+
if m[0] != self._CART or m[1] != self._CART:
|
| 1549 |
+
return ("control mode changed externally (left=%s right=%s); likely a self-collision monitor stop"
|
| 1550 |
+
% (m[0], m[1])), pair_d
|
| 1551 |
+
except Exception as e: # noqa: BLE001
|
| 1552 |
+
return "reading fault/mode failed: %s" % e, pair_d
|
| 1553 |
+
if pair_d < self.min_dist:
|
| 1554 |
+
return ("measured arm distance %.3f m < %.3f" % (pair_d, self.min_dist)), pair_d
|
| 1555 |
+
return None, pair_d
|
| 1556 |
+
|
| 1557 |
+
def _emergency_stop(self):
|
| 1558 |
+
try:
|
| 1559 |
+
if self._pair is not None and self._pair.operational():
|
| 1560 |
+
self._pair.Stop()
|
| 1561 |
+
except Exception as e: # noqa: BLE001
|
| 1562 |
+
log.error("emergency stop failed: %s", e)
|
| 1563 |
+
try:
|
| 1564 |
+
if self._grip is not None:
|
| 1565 |
+
self._grip.close()
|
| 1566 |
+
except Exception: # noqa: BLE001
|
| 1567 |
+
pass
|
flexiv-umi-infer/umi_infer/robot_io/gripper_can.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""Position servo for two grippers (Damiao motors on a CANalyst-II box).
|
| 4 |
+
|
| 5 |
+
Wiring: CAN1 = channel 0 = left gripper, CAN2 = channel 1 = right gripper; command ID 0x08 on both.
|
| 6 |
+
Codec, enable frames and bus I/O are reused from gripper_tool.
|
| 7 |
+
|
| 8 |
+
Scale: opening (dataset deg) = (q - q_closed_rad) * deg_per_rad, from the calibration file
|
| 9 |
+
(default data/gripper_calib.json). Datasets may use only part of the 0-90 deg range.
|
| 10 |
+
|
| 11 |
+
Bounded force: the command is clamped to [closed - overclose, open], then to measured +/- lead,
|
| 12 |
+
so max force ~= kp x rad(lead). Defaults kp=36 / kd=0.8, lead=5 deg -> ~3.1 Nm.
|
| 13 |
+
|
| 14 |
+
"Commanded closed" is not "gripping": position-control force = kp x position error. Commanding
|
| 15 |
+
0 deg targets q_closed, so the error is only as large as the object pushes the jaws open.
|
| 16 |
+
To grip, command past contact (below q_closed): set_floor(side, floor_deg) allows a negative
|
| 17 |
+
floor, hard-capped by OVERCLOSE_MAX_DEG. The inference-side close latch decides when.
|
| 18 |
+
|
| 19 |
+
Self-test (grippers only, arms untouched):
|
| 20 |
+
python -m umi_infer.robot_io.gripper_can --data <lerobot_root> --replay-episode 0
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import math
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
import threading
|
| 30 |
+
import time
|
| 31 |
+
|
| 32 |
+
from .gripper_tool import ( # noqa: E402 reuse low-level driver
|
| 33 |
+
DISABLE_FRAME, ENABLE_FRAME, IDLE, Motor,
|
| 34 |
+
drain, open_bus, pack_mit_command, send, wait_feedback,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
SIDES = ("left", "right")
|
| 38 |
+
CHANNEL = {"left": 0, "right": 1} # CAN1 left, CAN2 right
|
| 39 |
+
CMD_ID = {"left": 0x08, "right": 0x08}
|
| 40 |
+
DEFAULT_CALIB = os.environ.get("FLEXIV_GRIP_CALIB", os.path.join(
|
| 41 |
+
os.environ.get("UMI_INFER_DATA", "data"), "gripper_calib.json"))
|
| 42 |
+
# Hard cap on overclose (below calibrated closed), dataset deg; more would push into the hard stop.
|
| 43 |
+
# Force is still bounded by lead (kp x rad(lead)); overclose only lets the error reach that bound.
|
| 44 |
+
OVERCLOSE_MAX_DEG = 8.0
|
| 45 |
+
D = math.degrees
|
| 46 |
+
R = math.radians
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class GripperPair:
|
| 50 |
+
"""Position servo for both grippers. set_deg() stores the target; a thread sends MIT frames at rate_hz."""
|
| 51 |
+
|
| 52 |
+
def __init__(self, calib_path=DEFAULT_CALIB, kp=36.0, kd=0.8, lead_deg=5.0,
|
| 53 |
+
rate_hz=200.0, gain=1.0, logger=None):
|
| 54 |
+
with open(calib_path) as f:
|
| 55 |
+
cal = json.load(f)
|
| 56 |
+
missing = [s for s in SIDES if s not in cal]
|
| 57 |
+
if missing:
|
| 58 |
+
raise ValueError("calibration %s missing %s" % (calib_path, missing))
|
| 59 |
+
self.calib_path = calib_path
|
| 60 |
+
self.q_closed = {s: float(cal[s]["q_closed_rad"]) for s in SIDES}
|
| 61 |
+
self.q_open = {s: float(cal[s]["q_open_rad"]) for s in SIDES}
|
| 62 |
+
self.dpr = {s: float(cal[s]["deg_per_rad"]) for s in SIDES}
|
| 63 |
+
self.open_deg = {s: float(cal[s].get("open_deg",
|
| 64 |
+
abs(self.q_open[s] - self.q_closed[s]) * self.dpr[s]))
|
| 65 |
+
for s in SIDES}
|
| 66 |
+
self.kp, self.kd = float(kp), float(kd)
|
| 67 |
+
self.lead = R(float(lead_deg))
|
| 68 |
+
self.rate_hz = float(rate_hz)
|
| 69 |
+
self.gain = float(gain)
|
| 70 |
+
self.log = logger
|
| 71 |
+
self.motors = {s: Motor(CHANNEL[s], CMD_ID[s], CMD_ID[s] + 0x10) for s in SIDES}
|
| 72 |
+
self._by_key = {m.key: m for m in self.motors.values()}
|
| 73 |
+
self._target = {s: 0.0 for s in SIDES} # dataset deg
|
| 74 |
+
# Per-side floor (dataset deg). 0 = calibrated closed; negative = allow overclose.
|
| 75 |
+
self._floor = {s: 0.0 for s in SIDES}
|
| 76 |
+
self._sent = {s: None for s in SIDES} # last command actually sent (rad)
|
| 77 |
+
self._lock = threading.Lock()
|
| 78 |
+
self._stop = threading.Event()
|
| 79 |
+
self._thread = None
|
| 80 |
+
self.bus = None
|
| 81 |
+
self.enabled = False
|
| 82 |
+
|
| 83 |
+
# ---------------- lifecycle ----------------
|
| 84 |
+
def _info(self, msg):
|
| 85 |
+
if self.log is not None:
|
| 86 |
+
self.log.info(msg)
|
| 87 |
+
else:
|
| 88 |
+
print(msg, flush=True)
|
| 89 |
+
|
| 90 |
+
def _warn(self, msg):
|
| 91 |
+
if self.log is not None:
|
| 92 |
+
self.log.warn(msg)
|
| 93 |
+
else:
|
| 94 |
+
print("[warn] " + msg, flush=True)
|
| 95 |
+
|
| 96 |
+
def open(self):
|
| 97 |
+
"""Open the bus and require feedback from both motors. Not enabled; jaws can still be moved by hand."""
|
| 98 |
+
self.bus = open_bus(set(CHANNEL.values()), 1_000_000, 0)
|
| 99 |
+
ms = list(self.motors.values())
|
| 100 |
+
if not wait_feedback(self.bus, ms, self._by_key, timeout=2.0):
|
| 101 |
+
bad = [s for s in SIDES if self.motors[s].q is None]
|
| 102 |
+
self.close()
|
| 103 |
+
raise RuntimeError("no gripper feedback: %s; check CAN wiring / motor power, or run "
|
| 104 |
+
"gripper_tool scan" % ", ".join(bad))
|
| 105 |
+
self._info("gripper calibration %s" % self.calib_path)
|
| 106 |
+
for s in SIDES:
|
| 107 |
+
self._info(" %-5s opening %6.2f deg (closed %+.5f / open %+.5f rad, full open %.2f deg)"
|
| 108 |
+
% (s, self.measured_deg(s), self.q_closed[s], self.q_open[s],
|
| 109 |
+
self.open_deg[s]))
|
| 110 |
+
self._thread = threading.Thread(target=self._loop, daemon=True)
|
| 111 |
+
self._thread.start()
|
| 112 |
+
return self
|
| 113 |
+
|
| 114 |
+
def enable(self):
|
| 115 |
+
"""Enable motors. Before this the thread only sends zero-torque frames (for feedback)."""
|
| 116 |
+
for s in SIDES:
|
| 117 |
+
with self._lock:
|
| 118 |
+
for _ in range(3):
|
| 119 |
+
send(self.bus, self.motors[s], ENABLE_FRAME)
|
| 120 |
+
time.sleep(0.01)
|
| 121 |
+
self.enabled = True
|
| 122 |
+
self._info("grippers enabled: kp=%.1f kd=%.2f lead %.1f deg (~%.2f Nm) @ %.0f Hz gain %.2f"
|
| 123 |
+
% (self.kp, self.kd, D(self.lead), self.kp * self.lead,
|
| 124 |
+
self.rate_hz, self.gain))
|
| 125 |
+
|
| 126 |
+
def close(self):
|
| 127 |
+
"""Release torque, disable, close bus. Safe to call twice."""
|
| 128 |
+
self._stop.set()
|
| 129 |
+
if self._thread is not None:
|
| 130 |
+
self._thread.join(timeout=1.0)
|
| 131 |
+
self._thread = None
|
| 132 |
+
if self.bus is None:
|
| 133 |
+
return
|
| 134 |
+
try:
|
| 135 |
+
for s in SIDES:
|
| 136 |
+
for _ in range(5): # release torque first to avoid a jerk
|
| 137 |
+
send(self.bus, self.motors[s], IDLE)
|
| 138 |
+
time.sleep(0.005)
|
| 139 |
+
send(self.bus, self.motors[s], DISABLE_FRAME)
|
| 140 |
+
except Exception as e:
|
| 141 |
+
self._warn("gripper release/disable error: %s: %s" % (type(e).__name__, e))
|
| 142 |
+
finally:
|
| 143 |
+
try:
|
| 144 |
+
self.bus.shutdown()
|
| 145 |
+
except Exception:
|
| 146 |
+
pass
|
| 147 |
+
self.bus = None
|
| 148 |
+
self.enabled = False
|
| 149 |
+
self._info("grippers released and disabled")
|
| 150 |
+
|
| 151 |
+
def __enter__(self):
|
| 152 |
+
return self.open()
|
| 153 |
+
|
| 154 |
+
def __exit__(self, *exc):
|
| 155 |
+
self.close()
|
| 156 |
+
return False
|
| 157 |
+
|
| 158 |
+
# ---------------- command / readback ----------------
|
| 159 |
+
def set_deg(self, side, dataset_deg):
|
| 160 |
+
"""Target opening in dataset deg. Non-blocking."""
|
| 161 |
+
self._target[side] = float(dataset_deg)
|
| 162 |
+
|
| 163 |
+
def set_all(self, degs):
|
| 164 |
+
for s in SIDES:
|
| 165 |
+
self._target[s] = float(degs[s])
|
| 166 |
+
|
| 167 |
+
def set_floor(self, side, floor_deg):
|
| 168 |
+
"""Set one gripper's floor (negative = past calibrated closed -> grip force).
|
| 169 |
+
|
| 170 |
+
0 = default (calibrated closed). Capped by OVERCLOSE_MAX_DEG. See module docstring.
|
| 171 |
+
"""
|
| 172 |
+
f = float(floor_deg)
|
| 173 |
+
self._floor[side] = max(min(f, 0.0), -OVERCLOSE_MAX_DEG)
|
| 174 |
+
|
| 175 |
+
def set_floor_all(self, floors):
|
| 176 |
+
for s in SIDES:
|
| 177 |
+
self.set_floor(s, floors[s])
|
| 178 |
+
|
| 179 |
+
def floor_deg(self, side):
|
| 180 |
+
return float(self._floor[side])
|
| 181 |
+
|
| 182 |
+
def set_lead_deg(self, lead_deg):
|
| 183 |
+
"""Change the force bound (kp x rad(lead)) at runtime; raise this for more grip, not overclose."""
|
| 184 |
+
self.lead = R(max(0.5, float(lead_deg)))
|
| 185 |
+
|
| 186 |
+
def measured_deg(self, side):
|
| 187 |
+
q = self.motors[side].q
|
| 188 |
+
return float("nan") if q is None else (q - self.q_closed[side]) * self.dpr[side]
|
| 189 |
+
|
| 190 |
+
def commanded_deg(self, side):
|
| 191 |
+
q = self._sent[side]
|
| 192 |
+
return float("nan") if q is None else (q - self.q_closed[side]) * self.dpr[side]
|
| 193 |
+
|
| 194 |
+
def status_line(self):
|
| 195 |
+
def one(s):
|
| 196 |
+
# Tag from the actual command, not the floor: floor<0 only allows overclose.
|
| 197 |
+
c = self.commanded_deg(s)
|
| 198 |
+
tag = "" if not (c == c and c < 0) else "[overclose %.2f deg]" % (-c)
|
| 199 |
+
return "%s cmd%5.1f/meas%5.1f deg%s" % (s[0].upper(), c,
|
| 200 |
+
self.measured_deg(s), tag)
|
| 201 |
+
return " ".join(one(s) for s in SIDES)
|
| 202 |
+
|
| 203 |
+
def target_q(self, side):
|
| 204 |
+
"""Dataset deg -> motor angle (rad). Floor set by set_floor (default calibrated closed)."""
|
| 205 |
+
lo_deg = self._floor[side] # 0 or negative (overclose)
|
| 206 |
+
deg = min(max(self.gain * self._target[side], lo_deg), self.open_deg[side])
|
| 207 |
+
q = self.q_closed[side] + deg / self.dpr[side]
|
| 208 |
+
# Travel clamp: lower bound follows floor, upper bound fixed
|
| 209 |
+
q_floor = self.q_closed[side] + lo_deg / self.dpr[side]
|
| 210 |
+
lo, hi = sorted((q_floor, self.q_open[side]))
|
| 211 |
+
return min(hi, max(lo, q))
|
| 212 |
+
|
| 213 |
+
# ---------------- background servo ----------------
|
| 214 |
+
def _loop(self):
|
| 215 |
+
interval = 1.0 / self.rate_hz
|
| 216 |
+
nxt = time.monotonic()
|
| 217 |
+
while not self._stop.is_set():
|
| 218 |
+
now = time.monotonic()
|
| 219 |
+
if now < nxt:
|
| 220 |
+
time.sleep(min(interval * 0.25, max(0.0, nxt - now)))
|
| 221 |
+
continue
|
| 222 |
+
nxt = now + interval
|
| 223 |
+
try:
|
| 224 |
+
with self._lock:
|
| 225 |
+
drain(self.bus, self._by_key)
|
| 226 |
+
for s in SIDES:
|
| 227 |
+
m = self.motors[s]
|
| 228 |
+
if not self.enabled or m.q is None:
|
| 229 |
+
send(self.bus, m, IDLE) # not enabled: zero torque, feedback only
|
| 230 |
+
continue
|
| 231 |
+
q = self.target_q(s)
|
| 232 |
+
# Force bound: command may not lead measurement by more than lead
|
| 233 |
+
q = min(m.q + self.lead, max(m.q - self.lead, q))
|
| 234 |
+
self._sent[s] = q
|
| 235 |
+
send(self.bus, m, pack_mit_command(q, 0.0, self.kp, self.kd, 0.0))
|
| 236 |
+
except Exception as e:
|
| 237 |
+
self._warn("gripper servo thread error: %s: %s" % (type(e).__name__, e))
|
| 238 |
+
return
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# ---------------- self-test: grippers only, arms untouched ----------------
|
| 242 |
+
def _episode_grip(data_root, episode):
|
| 243 |
+
"""Read the two gripper columns and fps directly from parquet."""
|
| 244 |
+
import glob
|
| 245 |
+
|
| 246 |
+
import numpy as np
|
| 247 |
+
import pyarrow.parquet as pq
|
| 248 |
+
|
| 249 |
+
pat = os.path.join(data_root, "data", "**", "episode_%06d.parquet" % episode)
|
| 250 |
+
fs = glob.glob(pat, recursive=True)
|
| 251 |
+
if not fs:
|
| 252 |
+
raise FileNotFoundError("not found: %s" % pat)
|
| 253 |
+
st = np.stack(pq.read_table(fs[0], columns=["observation.state"])
|
| 254 |
+
["observation.state"].to_numpy())
|
| 255 |
+
with open(os.path.join(data_root, "meta", "info.json")) as f:
|
| 256 |
+
fps = float(json.load(f).get("fps", 30))
|
| 257 |
+
return {"left": st[:, 7].astype(float), "right": st[:, 15].astype(float)}, fps
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def main(argv=None):
|
| 261 |
+
import argparse
|
| 262 |
+
|
| 263 |
+
ap = argparse.ArgumentParser(description="Gripper ground-truth self-test: drives the two grippers only, not the arms")
|
| 264 |
+
ap.add_argument("--replay-episode", type=int, required=True, help="episode whose gripper ground truth to replay")
|
| 265 |
+
ap.add_argument("--data", required=True, help="LeRobot dataset root")
|
| 266 |
+
ap.add_argument("--calib", default=DEFAULT_CALIB)
|
| 267 |
+
ap.add_argument("--speed", type=float, default=0.3, help="time scale (default 0.3 = slowed down)")
|
| 268 |
+
ap.add_argument("--kp", type=float, default=36.0)
|
| 269 |
+
ap.add_argument("--kd", type=float, default=0.8)
|
| 270 |
+
ap.add_argument("--lead-deg", type=float, default=5.0)
|
| 271 |
+
ap.add_argument("--rate", type=float, default=200.0)
|
| 272 |
+
ap.add_argument("--gain", type=float, default=1.0)
|
| 273 |
+
ap.add_argument("--yes", action="store_true", help="confirm actually driving the grippers")
|
| 274 |
+
args = ap.parse_args(argv)
|
| 275 |
+
|
| 276 |
+
grip_src, fps = _episode_grip(args.data, args.replay_episode)
|
| 277 |
+
n = len(grip_src["left"])
|
| 278 |
+
dur = (n - 1) / fps / args.speed
|
| 279 |
+
print("ep%04d %d frames @ %.0f fps speed %.2f -> %.1f s" % (args.replay_episode, n, fps,
|
| 280 |
+
args.speed, dur))
|
| 281 |
+
for s in SIDES:
|
| 282 |
+
g = grip_src[s]
|
| 283 |
+
print(" %-5s ground truth %.2f ~ %.2f deg range %.2f deg" % (s, g.min(), g.max(), g.max() - g.min()))
|
| 284 |
+
if not args.yes:
|
| 285 |
+
sys.exit("This drives the grippers. Make sure nobody touches the jaws, then rerun with --yes.")
|
| 286 |
+
|
| 287 |
+
g = GripperPair(args.calib, kp=args.kp, kd=args.kd, lead_deg=args.lead_deg,
|
| 288 |
+
rate_hz=args.rate, gain=args.gain)
|
| 289 |
+
with g:
|
| 290 |
+
g.set_all({s: grip_src[s][0] for s in SIDES})
|
| 291 |
+
print("\nWARNING: hands off the jaws. Enter to start, Ctrl-C to stop.", end="")
|
| 292 |
+
try:
|
| 293 |
+
input()
|
| 294 |
+
except (EOFError, KeyboardInterrupt):
|
| 295 |
+
print("\ncancelled")
|
| 296 |
+
return 1
|
| 297 |
+
g.enable()
|
| 298 |
+
time.sleep(0.5) # settle at first-frame opening
|
| 299 |
+
t0 = time.monotonic()
|
| 300 |
+
last_i, last_log = -1, 0.0
|
| 301 |
+
try:
|
| 302 |
+
while True:
|
| 303 |
+
t = (time.monotonic() - t0) * args.speed
|
| 304 |
+
i = int(round(t * fps))
|
| 305 |
+
if i >= n:
|
| 306 |
+
break
|
| 307 |
+
if i != last_i:
|
| 308 |
+
last_i = i
|
| 309 |
+
g.set_all({s: grip_src[s][i] for s in SIDES})
|
| 310 |
+
now = time.monotonic()
|
| 311 |
+
if now - last_log >= 0.2:
|
| 312 |
+
last_log = now
|
| 313 |
+
print(" t=%6.2fs %5d/%d %s " % (t / args.speed, i, n,
|
| 314 |
+
g.status_line()), end="\r", flush=True)
|
| 315 |
+
time.sleep(0.002)
|
| 316 |
+
print("\nreplay done")
|
| 317 |
+
except KeyboardInterrupt:
|
| 318 |
+
print("\nCtrl-C")
|
| 319 |
+
return 0
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
if __name__ == "__main__":
|
| 323 |
+
sys.exit(main())
|
flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""Standalone gripper motor tool (CANalyst-II + Damiao MIT protocol).
|
| 4 |
+
|
| 5 |
+
Touches only the gripper motors: no flexivrdk import, no arm connection.
|
| 6 |
+
scan / read keep motors DISABLED (zero-torque frames only, to get feedback); jaws can be
|
| 7 |
+
moved by hand. Only sweep / goto enable motors, and require --yes plus Enter.
|
| 8 |
+
|
| 9 |
+
Motor zero is not assumed to be "closed", so sweep/goto limits are relative to the start position.
|
| 10 |
+
|
| 11 |
+
Motor spec: <channel>:<cmd_id>[:<fb_id>] fb_id defaults to cmd_id + 0x10
|
| 12 |
+
CAN box CAN1 = channel 0 = left gripper, CAN2 = channel 1 = right gripper:
|
| 13 |
+
0:8 CAN1 left, cmd 0x08, feedback 0x18
|
| 14 |
+
1:8 CAN2 right
|
| 15 |
+
0:8:0x18 explicit feedback ID
|
| 16 |
+
|
| 17 |
+
Bounded force: the target is always clamped to measured +/- lead, so max force ~= kp x lead (rad),
|
| 18 |
+
printed at start. Hitting a hard stop is a soft push, not a slam.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import math
|
| 25 |
+
import os
|
| 26 |
+
import sys
|
| 27 |
+
import time
|
| 28 |
+
|
| 29 |
+
# ── Damiao MIT codec ──────────────────────────────────────────────────────────
|
| 30 |
+
P_MAX, V_MAX, T_MAX = 12.5, 30.0, 10.0 # command range = DM4310 Limit_Param
|
| 31 |
+
F_P_MAX, F_V_MAX, F_T_MAX = 12.5, 30.0, 10.0 # feedback range
|
| 32 |
+
KP_MAX, KD_MAX = 500.0, 5.0
|
| 33 |
+
ENABLE_FRAME = bytes([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC])
|
| 34 |
+
DISABLE_FRAME = bytes([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _limit(x, lo, hi):
|
| 38 |
+
return lo if x < lo else hi if x > hi else x
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _f2u(x, lo, hi, bits):
|
| 42 |
+
x = _limit(x, lo, hi)
|
| 43 |
+
return int(round((x - lo) * ((1 << bits) - 1) / (hi - lo)))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _u2f(x, lo, hi, bits):
|
| 47 |
+
return float(x) * (hi - lo) / ((1 << bits) - 1) + lo
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def pack_mit_command(q, dq, kp, kd, tau) -> bytes:
|
| 51 |
+
p_int = _f2u(q, -P_MAX, P_MAX, 16)
|
| 52 |
+
v_int = _f2u(dq, -V_MAX, V_MAX, 12)
|
| 53 |
+
kp_int = _f2u(kp, 0.0, KP_MAX, 12)
|
| 54 |
+
kd_int = _f2u(kd, 0.0, KD_MAX, 12)
|
| 55 |
+
t_int = _f2u(tau, -T_MAX, T_MAX, 12)
|
| 56 |
+
d = bytearray(8)
|
| 57 |
+
d[0] = (p_int >> 8) & 0xFF
|
| 58 |
+
d[1] = p_int & 0xFF
|
| 59 |
+
d[2] = (v_int >> 4) & 0xFF
|
| 60 |
+
d[3] = ((v_int & 0x0F) << 4) | ((kp_int >> 8) & 0x0F)
|
| 61 |
+
d[4] = kp_int & 0xFF
|
| 62 |
+
d[5] = (kd_int >> 4) & 0xFF
|
| 63 |
+
d[6] = ((kd_int & 0x0F) << 4) | ((t_int >> 8) & 0x0F)
|
| 64 |
+
d[7] = t_int & 0xFF
|
| 65 |
+
return bytes(d)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def parse_mit_feedback(data):
|
| 69 |
+
p_int = (data[1] << 8) | data[2]
|
| 70 |
+
v_int = (data[3] << 4) | (data[4] >> 4)
|
| 71 |
+
t_int = ((data[4] & 0x0F) << 8) | data[5]
|
| 72 |
+
return (_u2f(p_int, -F_P_MAX, F_P_MAX, 16),
|
| 73 |
+
_u2f(v_int, -F_V_MAX, F_V_MAX, 12),
|
| 74 |
+
_u2f(t_int, -F_T_MAX, F_T_MAX, 12))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
IDLE = pack_mit_command(0.0, 0.0, 0.0, 0.0, 0.0) # zero torque: motor replies with feedback even when disabled
|
| 78 |
+
D = math.degrees
|
| 79 |
+
R = math.radians
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ── motors ────────────────────────────────────────────────────────────────────
|
| 83 |
+
# CAN box CAN1/CAN2 = software channel 0/1. Wiring: CAN1 left gripper, CAN2 right gripper.
|
| 84 |
+
SIDE = {0: "left", 1: "right"}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Motor:
|
| 88 |
+
def __init__(self, ch, cmd_id, fb_id, name=""):
|
| 89 |
+
self.ch, self.cmd_id, self.fb_id = ch, cmd_id, fb_id
|
| 90 |
+
self.name = name or "%s gripper (CAN%d 0x%02X)" % (SIDE.get(ch, "?"), ch + 1, cmd_id)
|
| 91 |
+
self.q = self.dq = self.tau = None
|
| 92 |
+
self.n = 0
|
| 93 |
+
self.t_last = 0.0
|
| 94 |
+
self.enabled = False
|
| 95 |
+
# control state
|
| 96 |
+
self.q_start = None
|
| 97 |
+
self.q_des = None
|
| 98 |
+
self.dirn = 1
|
| 99 |
+
self.q_ref = None
|
| 100 |
+
self.q_ref_t = 0.0
|
| 101 |
+
self.done = False
|
| 102 |
+
self.why = ""
|
| 103 |
+
self.rev = [] # one entry per reversal: (angle, direction, real stop or travel cap)
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def key(self):
|
| 107 |
+
return (self.ch, self.fb_id)
|
| 108 |
+
|
| 109 |
+
def __str__(self):
|
| 110 |
+
return self.name
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def parse_motor(spec):
|
| 114 |
+
parts = spec.split(":")
|
| 115 |
+
if not 2 <= len(parts) <= 3:
|
| 116 |
+
raise argparse.ArgumentTypeError("motor spec must be channel:cmd_id[:fb_id], got %r" % spec)
|
| 117 |
+
ch = int(parts[0], 0)
|
| 118 |
+
cmd = int(parts[1], 0)
|
| 119 |
+
fb = int(parts[2], 0) if len(parts) == 3 else cmd + 0x10
|
| 120 |
+
if ch not in (0, 1):
|
| 121 |
+
raise argparse.ArgumentTypeError("CANalyst-II has only channels 0/1, got %d" % ch)
|
| 122 |
+
return Motor(ch, cmd, fb)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ── bus ───────────────────────────────────────────────────────────────────────
|
| 126 |
+
def open_bus(channels, bitrate, device):
|
| 127 |
+
try:
|
| 128 |
+
import can
|
| 129 |
+
except ImportError:
|
| 130 |
+
sys.exit("python-can missing. Install: pip "
|
| 131 |
+
"install python-can canalystii")
|
| 132 |
+
try:
|
| 133 |
+
return can.Bus(interface="canalystii", channel=tuple(sorted(channels)),
|
| 134 |
+
bitrate=bitrate, device=device)
|
| 135 |
+
except Exception as e:
|
| 136 |
+
sys.exit("cannot open CANalyst-II (channels %s): %s\n"
|
| 137 |
+
"-> most likely USB permissions: run with sudo, or see the udev rule in --help."
|
| 138 |
+
% (sorted(channels), e))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def send(bus, m, data):
|
| 142 |
+
import can
|
| 143 |
+
bus.send(can.Message(arbitration_id=m.cmd_id, is_extended_id=False,
|
| 144 |
+
data=data, channel=m.ch))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def drain(bus, by_key, limit=512, unknown=None):
|
| 148 |
+
"""Dispatch received frames to their motors. Returns the number of matched frames."""
|
| 149 |
+
got = 0
|
| 150 |
+
for _ in range(limit):
|
| 151 |
+
msg = bus.recv(timeout=0.0)
|
| 152 |
+
if msg is None:
|
| 153 |
+
break
|
| 154 |
+
m = by_key.get((msg.channel, msg.arbitration_id))
|
| 155 |
+
if m is not None and msg.dlc == 8:
|
| 156 |
+
m.q, m.dq, m.tau = parse_mit_feedback(msg.data)
|
| 157 |
+
m.n += 1
|
| 158 |
+
m.t_last = time.time()
|
| 159 |
+
got += 1
|
| 160 |
+
elif unknown is not None:
|
| 161 |
+
unknown.setdefault((msg.channel, msg.arbitration_id), 0)
|
| 162 |
+
unknown[(msg.channel, msg.arbitration_id)] += 1
|
| 163 |
+
return got
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def wait_feedback(bus, motors, by_key, timeout=2.0):
|
| 167 |
+
"""Query current angles with zero-torque frames. Motors stay disabled."""
|
| 168 |
+
t0 = time.time()
|
| 169 |
+
while time.time() - t0 < timeout:
|
| 170 |
+
for m in motors:
|
| 171 |
+
send(bus, m, IDLE)
|
| 172 |
+
time.sleep(0.02)
|
| 173 |
+
drain(bus, by_key)
|
| 174 |
+
if all(m.q is not None for m in motors):
|
| 175 |
+
return True
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ── scan: channels x IDs, find motors online ──────────────────────────────────
|
| 180 |
+
def cmd_scan(args):
|
| 181 |
+
ids = range(args.id_min, args.id_max + 1)
|
| 182 |
+
chans = args.channels
|
| 183 |
+
bus = open_bus(chans, args.bitrate, args.device)
|
| 184 |
+
print("scanning channels %s, cmd ID 0x%02X..0x%02X, feedback ID default = cmd ID + 0x10"
|
| 185 |
+
% (list(chans), args.id_min, args.id_max))
|
| 186 |
+
print("motors stay disabled, zero-torque frames only; jaws will not move\n")
|
| 187 |
+
try:
|
| 188 |
+
# Listen quietly for 0.4 s first: any unsolicited traffic?
|
| 189 |
+
quiet = {}
|
| 190 |
+
t0 = time.time()
|
| 191 |
+
while time.time() - t0 < 0.4:
|
| 192 |
+
drain(bus, {}, unknown=quiet)
|
| 193 |
+
time.sleep(0.01)
|
| 194 |
+
if quiet:
|
| 195 |
+
print("unsolicited traffic already on the bus:")
|
| 196 |
+
for (ch, aid), n in sorted(quiet.items()):
|
| 197 |
+
print(" ch%d ID 0x%03X %d frames" % (ch, aid, n))
|
| 198 |
+
print()
|
| 199 |
+
|
| 200 |
+
found = []
|
| 201 |
+
for ch in chans:
|
| 202 |
+
for cid in ids:
|
| 203 |
+
m = Motor(ch, cid, cid + 0x10)
|
| 204 |
+
by_key = {}
|
| 205 |
+
seen = {}
|
| 206 |
+
# Record replies on any ID (feedback ID is not always +0x10)
|
| 207 |
+
t0 = time.time()
|
| 208 |
+
while time.time() - t0 < args.dwell:
|
| 209 |
+
send(bus, m, IDLE)
|
| 210 |
+
time.sleep(0.01)
|
| 211 |
+
drain(bus, by_key, unknown=seen)
|
| 212 |
+
if seen:
|
| 213 |
+
for (rch, aid), n in sorted(seen.items()):
|
| 214 |
+
tag = " (= cmd ID+0x10)" if aid == cid + 0x10 else ""
|
| 215 |
+
print("OK ch%d cmd 0x%02X -> feedback ch%d ID 0x%03X %d frames%s"
|
| 216 |
+
% (ch, cid, rch, aid, n, tag))
|
| 217 |
+
found.append((ch, cid, rch, aid))
|
| 218 |
+
print()
|
| 219 |
+
if not found:
|
| 220 |
+
print("No motor responded. Check: (1) motor 24V power (2) CAN_H/CAN_L and ground (3) termination resistor/DIP "
|
| 221 |
+
"(4) bitrate (now %d) (5) which CANalyst channel the cable is on" % args.bitrate)
|
| 222 |
+
else:
|
| 223 |
+
print("%d motor(s) online:" % len(found))
|
| 224 |
+
for ch, cid, rch, aid in found:
|
| 225 |
+
print(" --motor %d:0x%02X%s" % (ch, cid, "" if aid == cid + 0x10
|
| 226 |
+
else ":0x%02X" % aid))
|
| 227 |
+
chs = {ch for ch, _, _, _ in found}
|
| 228 |
+
cids = {cid for _, cid, _, _ in found}
|
| 229 |
+
if len(found) >= 2 and len(chs) == 1 and len(cids) == 1:
|
| 230 |
+
print("\nWARNING: only one ID seen on one channel. Two grippers both at 0x08 on the same channel"
|
| 231 |
+
"\n collide on the bus; change one ID (or move it to the other channel).")
|
| 232 |
+
finally:
|
| 233 |
+
bus.shutdown()
|
| 234 |
+
return 0
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ── read: passive angle readout (motors disabled) ─────────────────────────────
|
| 238 |
+
def cmd_read(args):
|
| 239 |
+
motors = args.motor
|
| 240 |
+
by_key = {m.key: m for m in motors}
|
| 241 |
+
bus = open_bus({m.ch for m in motors}, args.bitrate, args.device)
|
| 242 |
+
print("passive read %s; motors disabled, zero torque, move jaws by hand. Ctrl-C to exit\n"
|
| 243 |
+
% ", ".join(str(m) for m in motors))
|
| 244 |
+
interval = 1.0 / args.rate_hz
|
| 245 |
+
t_end = time.time() + args.seconds if args.seconds > 0 else None
|
| 246 |
+
last_cmd = last_print = 0.0
|
| 247 |
+
try:
|
| 248 |
+
while t_end is None or time.time() < t_end:
|
| 249 |
+
now = time.time()
|
| 250 |
+
if now - last_cmd >= interval:
|
| 251 |
+
for m in motors:
|
| 252 |
+
send(bus, m, IDLE)
|
| 253 |
+
last_cmd = now
|
| 254 |
+
drain(bus, by_key)
|
| 255 |
+
if now - last_print >= 0.1:
|
| 256 |
+
last_print = now
|
| 257 |
+
cols = []
|
| 258 |
+
for m in motors:
|
| 259 |
+
if m.q is None:
|
| 260 |
+
cols.append("%s no feedback" % m)
|
| 261 |
+
else:
|
| 262 |
+
cols.append("%s %+8.2f deg dq%+6.2f tau%+5.2f" % (m, D(m.q), m.dq, m.tau))
|
| 263 |
+
print(" " + " | ".join(cols) + " ", end="\r", flush=True)
|
| 264 |
+
time.sleep(0.0005)
|
| 265 |
+
except KeyboardInterrupt:
|
| 266 |
+
pass
|
| 267 |
+
finally:
|
| 268 |
+
print()
|
| 269 |
+
for m in motors:
|
| 270 |
+
print("%s: received %d frames%s" % (m, m.n,
|
| 271 |
+
"" if m.q is None else ", last %+.2f deg" % D(m.q)))
|
| 272 |
+
bus.shutdown()
|
| 273 |
+
return 0
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ── shared control loop (motors enabled) ──────────────────────────────────────
|
| 277 |
+
def drive(bus, motors, by_key, args, mode):
|
| 278 |
+
"""mode='sweep': back-and-forth; mode='goto': move to relative target. Force bound kp*lead."""
|
| 279 |
+
lead = R(args.lead_deg)
|
| 280 |
+
speed = R(args.speed_deg)
|
| 281 |
+
eps = R(args.progress_deg)
|
| 282 |
+
interval = 1.0 / args.rate_hz
|
| 283 |
+
|
| 284 |
+
print("\nparams: kp=%.1f kd=%.2f lead=%.1f deg -> max force ~= %.2f Nm, speed %.0f deg/s"
|
| 285 |
+
% (args.kp, args.kd, args.lead_deg, args.kp * lead, args.speed_deg))
|
| 286 |
+
for m in motors:
|
| 287 |
+
m.q_start = m.q
|
| 288 |
+
m.q_des = m.q
|
| 289 |
+
m.q_ref = m.q
|
| 290 |
+
m.q_ref_t = time.time()
|
| 291 |
+
if mode == "sweep":
|
| 292 |
+
m.lo, m.hi = m.q - R(args.range_deg), m.q + R(args.range_deg)
|
| 293 |
+
m.dirn = -1 if getattr(args, "start_dir", "close") == "close" else 1
|
| 294 |
+
print(" %s start %+.2f deg, travel cap [%+.1f, %+.1f] deg, first toward %s"
|
| 295 |
+
% (m, D(m.q), D(m.lo) - D(m.q_start), D(m.hi) - D(m.q_start),
|
| 296 |
+
"close (neg)" if m.dirn < 0 else "open (pos)"))
|
| 297 |
+
else:
|
| 298 |
+
tgt = m.q + R(args.delta_deg)
|
| 299 |
+
m.lo, m.hi = min(m.q, tgt) - R(2.0), max(m.q, tgt) + R(2.0)
|
| 300 |
+
m.dirn = 1 if args.delta_deg >= 0 else -1
|
| 301 |
+
print(" %s start %+.2f deg -> target %+.2f deg (relative %+.1f deg)"
|
| 302 |
+
% (m, D(m.q), D(tgt), args.delta_deg))
|
| 303 |
+
if abs(m.q) > 11.0:
|
| 304 |
+
print(" WARNING: %s at %+.2f rad is near the +/-12.5 rad feedback wrap-around; turn it back by hand first"
|
| 305 |
+
% (m, m.q))
|
| 306 |
+
return 1
|
| 307 |
+
|
| 308 |
+
print("\nWARNING: hands off the jaws. Enter to start, Ctrl-C to stop (releases torque, then disables).", end="")
|
| 309 |
+
try:
|
| 310 |
+
input()
|
| 311 |
+
except (EOFError, KeyboardInterrupt):
|
| 312 |
+
print("\ncancelled, motors not enabled.")
|
| 313 |
+
return 1
|
| 314 |
+
|
| 315 |
+
for m in motors:
|
| 316 |
+
for _ in range(3):
|
| 317 |
+
send(bus, m, ENABLE_FRAME)
|
| 318 |
+
time.sleep(0.01)
|
| 319 |
+
m.enabled = True
|
| 320 |
+
print("enabled, moving.\n")
|
| 321 |
+
|
| 322 |
+
last_cmd = time.time()
|
| 323 |
+
t0 = time.time()
|
| 324 |
+
last_print = 0.0
|
| 325 |
+
while True:
|
| 326 |
+
now = time.time()
|
| 327 |
+
drain(bus, by_key)
|
| 328 |
+
if args.timeout > 0 and now - t0 > args.timeout:
|
| 329 |
+
print("\ntimeout %.0fs reached, stopping." % args.timeout)
|
| 330 |
+
break
|
| 331 |
+
if all(m.done for m in motors):
|
| 332 |
+
break
|
| 333 |
+
if now - last_cmd >= interval:
|
| 334 |
+
dt = now - last_cmd
|
| 335 |
+
last_cmd = now
|
| 336 |
+
for m in motors:
|
| 337 |
+
if m.done or m.q is None:
|
| 338 |
+
continue
|
| 339 |
+
if now - m.t_last > 0.3:
|
| 340 |
+
m.done, m.why = True, "feedback lost"
|
| 341 |
+
continue
|
| 342 |
+
m.q_des += m.dirn * speed * dt
|
| 343 |
+
m.q_des = min(m.q + lead, max(m.q - lead, m.q_des)) # force bound
|
| 344 |
+
m.q_des = min(m.hi, max(m.lo, m.q_des)) # absolute travel cap
|
| 345 |
+
# Progress watchdog: pushing and no net motion for a while -> at a stop
|
| 346 |
+
if abs(m.q - m.q_ref) >= eps:
|
| 347 |
+
m.q_ref, m.q_ref_t = m.q, now
|
| 348 |
+
stuck = (now - m.q_ref_t) >= args.stall_time
|
| 349 |
+
err = m.q_des - m.q
|
| 350 |
+
pushing = (err >= 0.8 * lead) if m.dirn > 0 else (err <= -0.8 * lead)
|
| 351 |
+
at_edge = (m.q_des >= m.hi - 1e-4) if m.dirn > 0 else (m.q_des <= m.lo + 1e-4)
|
| 352 |
+
if mode == "sweep":
|
| 353 |
+
if at_edge or (pushing and stuck):
|
| 354 |
+
why = "travel cap" if at_edge else "hit hard stop"
|
| 355 |
+
m.rev.append((m.q, m.dirn, not at_edge))
|
| 356 |
+
print(" %s reversal #%d @ %+7.2f deg tau%+5.2f Nm (%s)"
|
| 357 |
+
% (m, len(m.rev), D(m.q), m.tau, why))
|
| 358 |
+
m.dirn = -m.dirn
|
| 359 |
+
m.q_des, m.q_ref, m.q_ref_t = m.q, m.q, now
|
| 360 |
+
need = getattr(args, "reversals", 0)
|
| 361 |
+
if need and len(m.rev) >= need:
|
| 362 |
+
m.done, m.why = True, "done after %d reversals" % len(m.rev)
|
| 363 |
+
else:
|
| 364 |
+
reached = (abs(m.q_des - (m.q_start + R(args.delta_deg))) < 1e-4
|
| 365 |
+
and abs(m.q - m.q_des) < R(args.tol_deg))
|
| 366 |
+
if reached:
|
| 367 |
+
m.done, m.why = True, "reached"
|
| 368 |
+
elif pushing and stuck:
|
| 369 |
+
m.done, m.why = True, "blocked (hard stop or object)"
|
| 370 |
+
send(bus, m, pack_mit_command(m.q_des, 0.0, args.kp, args.kd, 0.0))
|
| 371 |
+
if now - last_print >= 0.2:
|
| 372 |
+
last_print = now
|
| 373 |
+
print(" " + " | ".join(
|
| 374 |
+
"%s %+8.2f deg (rel %+7.2f deg) tau%+5.2f%s"
|
| 375 |
+
% (m, D(m.q), D(m.q - m.q_start), m.tau,
|
| 376 |
+
" [%s]" % m.why if m.done else "")
|
| 377 |
+
for m in motors if m.q is not None) + " ", end="\r", flush=True)
|
| 378 |
+
time.sleep(0.0005)
|
| 379 |
+
print()
|
| 380 |
+
for m in motors:
|
| 381 |
+
print("%s: stopped at %+.2f deg (rel to start %+.2f deg) %s"
|
| 382 |
+
% (m, D(m.q), D(m.q - m.q_start), m.why))
|
| 383 |
+
if args.hold > 0:
|
| 384 |
+
print("holding %.1fs ..." % args.hold)
|
| 385 |
+
t1 = time.time()
|
| 386 |
+
while time.time() - t1 < args.hold:
|
| 387 |
+
for m in motors:
|
| 388 |
+
send(bus, m, pack_mit_command(m.q_des, 0.0, args.kp, args.kd, 0.0))
|
| 389 |
+
time.sleep(interval)
|
| 390 |
+
drain(bus, by_key)
|
| 391 |
+
return 0
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def relax_and_disable(bus, motors):
|
| 395 |
+
for m in motors:
|
| 396 |
+
if not m.enabled:
|
| 397 |
+
continue
|
| 398 |
+
try:
|
| 399 |
+
for _ in range(5): # release torque before disabling to avoid a jerk
|
| 400 |
+
send(bus, m, IDLE)
|
| 401 |
+
time.sleep(0.005)
|
| 402 |
+
send(bus, m, DISABLE_FRAME)
|
| 403 |
+
except Exception:
|
| 404 |
+
pass
|
| 405 |
+
print("torque released + disabled; jaws can be moved by hand.")
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _run_active(args, mode, post=None):
|
| 409 |
+
if not args.yes:
|
| 410 |
+
sys.exit("This drives the grippers. Make sure nobody touches the jaws, then rerun with --yes.")
|
| 411 |
+
motors = args.motor
|
| 412 |
+
by_key = {m.key: m for m in motors}
|
| 413 |
+
bus = open_bus({m.ch for m in motors}, args.bitrate, args.device)
|
| 414 |
+
rc = 1
|
| 415 |
+
try:
|
| 416 |
+
if not wait_feedback(bus, motors, by_key):
|
| 417 |
+
bad = [str(m) for m in motors if m.q is None]
|
| 418 |
+
print("no feedback: %s -> run scan first to check channel/ID" % ", ".join(bad))
|
| 419 |
+
return 1
|
| 420 |
+
rc = drive(bus, motors, by_key, args, mode)
|
| 421 |
+
except KeyboardInterrupt:
|
| 422 |
+
print("\n\nCtrl-C interrupted")
|
| 423 |
+
finally:
|
| 424 |
+
relax_and_disable(bus, motors)
|
| 425 |
+
bus.shutdown()
|
| 426 |
+
if post is not None:
|
| 427 |
+
rc = post(args, motors) or rc
|
| 428 |
+
return rc
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def cmd_sweep(args):
|
| 432 |
+
return _run_active(args, "sweep")
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# ── calib: push both ends at low force, take the stops = recalibrate open/close ──
|
| 436 |
+
JSON_SIDE = {0: "left", 1: "right"}
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def write_calib(args, motors):
|
| 440 |
+
"""Turn reversal angles into closed/open positions. Convention: negative direction = closing."""
|
| 441 |
+
import json
|
| 442 |
+
import os
|
| 443 |
+
|
| 444 |
+
out = {"meta": {"created": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 445 |
+
"script": os.path.basename(__file__),
|
| 446 |
+
"convention": "negative angle = closing; CAN1 (ch0) = left gripper, CAN2 (ch1) = right gripper",
|
| 447 |
+
"kp": args.kp, "lead_deg": args.lead_deg,
|
| 448 |
+
"max_force_Nm": round(args.kp * R(args.lead_deg), 3),
|
| 449 |
+
"scale": ("full open = measured travel in deg (deg_per_rad = 57.2958, i.e. opening = "
|
| 450 |
+
"true motor angle from closed)" if not args.open_deg else
|
| 451 |
+
"full open = given %.1f deg (external scale)" % args.open_deg),
|
| 452 |
+
"gripper_deg": "(q8 - q_closed_rad) * deg_per_rad"}}
|
| 453 |
+
bad = False
|
| 454 |
+
print()
|
| 455 |
+
for m in motors:
|
| 456 |
+
side = JSON_SIDE.get(m.ch, "ch%d" % m.ch)
|
| 457 |
+
closed = [q for q, d, _ in m.rev if d < 0] # blocked moving negative = closed end
|
| 458 |
+
opened = [q for q, d, _ in m.rev if d > 0]
|
| 459 |
+
soft = [r for r in m.rev if not r[2]]
|
| 460 |
+
if not closed or not opened:
|
| 461 |
+
print("%s calibration failed: closed end %d hits / open end %d hits; need at least one at each end"
|
| 462 |
+
% (m, len(closed), len(opened)))
|
| 463 |
+
bad = True
|
| 464 |
+
continue
|
| 465 |
+
q_closed = sum(closed) / len(closed)
|
| 466 |
+
q_open = sum(opened) / len(opened)
|
| 467 |
+
travel = q_open - q_closed
|
| 468 |
+
sp_c = D(max(closed) - min(closed)) if len(closed) > 1 else 0.0
|
| 469 |
+
sp_o = D(max(opened) - min(opened)) if len(opened) > 1 else 0.0
|
| 470 |
+
# Default scale = measured travel (deg_per_rad = 57.2958);
|
| 471 |
+
# --open-deg defines full open on an external scale (e.g. 90).
|
| 472 |
+
open_deg = args.open_deg if args.open_deg else D(travel)
|
| 473 |
+
rec = {"q_closed_rad": round(q_closed, 6), "q_open_rad": round(q_open, 6),
|
| 474 |
+
"travel_rad": round(travel, 6), "open_deg": round(open_deg, 4),
|
| 475 |
+
"deg_per_rad": round(open_deg / travel, 4) if travel else None,
|
| 476 |
+
"n_closed_hits": len(closed), "n_open_hits": len(opened),
|
| 477 |
+
"repeat_closed_deg": round(sp_c, 2), "repeat_open_deg": round(sp_o, 2)}
|
| 478 |
+
out[side] = rec
|
| 479 |
+
print("%s closed %+.5f rad (%+7.2f deg) open %+.5f rad (%+7.2f deg) travel %.2f deg"
|
| 480 |
+
% (m, q_closed, D(q_closed), q_open, D(q_open), D(travel)))
|
| 481 |
+
print(" repeatability closed +/-%.2f deg open +/-%.2f deg full open %.2f deg -> 1 rad = %.4f deg"
|
| 482 |
+
% (sp_c, sp_o, open_deg, open_deg / travel if travel else float("nan")))
|
| 483 |
+
if max(sp_c, sp_o) > args.spread_tol:
|
| 484 |
+
print(" WARNING: repeatability worse than %.1f deg; force too low / pause mistaken for a stop, raise --kp and redo"
|
| 485 |
+
% args.spread_tol)
|
| 486 |
+
bad = True
|
| 487 |
+
if travel <= 0:
|
| 488 |
+
print(" WARNING: negative travel; closing direction is reversed, redo with --start-dir open")
|
| 489 |
+
bad = True
|
| 490 |
+
if soft:
|
| 491 |
+
print(" WARNING: %d reversal(s) hit the --range-deg cap instead of a hard stop; raise --range-deg"
|
| 492 |
+
% len(soft))
|
| 493 |
+
bad = True
|
| 494 |
+
if len(out) > 1:
|
| 495 |
+
os.makedirs(os.path.dirname(args.out), exist_ok=True)
|
| 496 |
+
with open(args.out, "w") as f:
|
| 497 |
+
json.dump(out, f, indent=1, ensure_ascii=False)
|
| 498 |
+
print("\nwrote %s%s" % (args.out, " (with warnings, see above)" if bad else ""))
|
| 499 |
+
return 1 if bad else 0
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def cmd_calib(args):
|
| 503 |
+
return _run_active(args, "sweep", post=write_calib)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def cmd_recompute(args):
|
| 507 |
+
"""Recompute the scale only, no hardware; measured closed/open/travel are kept as is."""
|
| 508 |
+
import json
|
| 509 |
+
|
| 510 |
+
with open(args.file) as f:
|
| 511 |
+
cal = json.load(f)
|
| 512 |
+
for side in ("left", "right"):
|
| 513 |
+
rec = cal.get(side)
|
| 514 |
+
if not rec:
|
| 515 |
+
continue
|
| 516 |
+
travel = rec["travel_rad"]
|
| 517 |
+
open_deg = args.open_deg if args.open_deg else D(travel)
|
| 518 |
+
rec["open_deg"] = round(open_deg, 4)
|
| 519 |
+
rec["deg_per_rad"] = round(open_deg / travel, 4)
|
| 520 |
+
print("%-5s travel %.2f deg full open set to %.2f deg -> 1 rad = %.4f deg"
|
| 521 |
+
% (side, D(travel), open_deg, open_deg / travel))
|
| 522 |
+
cal.setdefault("meta", {}).pop("jaw_travel_deg", None) # drop legacy 90-deg assumption
|
| 523 |
+
cal["meta"]["scale"] = (
|
| 524 |
+
"full open = measured travel in deg (deg_per_rad = 57.2958, i.e. opening = true motor angle from closed)"
|
| 525 |
+
if not args.open_deg else "full open = given %.1f deg (external scale)" % args.open_deg)
|
| 526 |
+
cal["meta"]["scale_recomputed"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 527 |
+
out = args.out or args.file
|
| 528 |
+
with open(out, "w") as f:
|
| 529 |
+
json.dump(cal, f, indent=1, ensure_ascii=False)
|
| 530 |
+
print("wrote %s" % out)
|
| 531 |
+
return 0
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def cmd_goto(args):
|
| 535 |
+
return _run_active(args, "goto")
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
# ── CLI ───────────────────────────────────────────────────────────────────────
|
| 539 |
+
EXAMPLES = """
|
| 540 |
+
Examples (USB access may need sudo, or the udev rule below):
|
| 541 |
+
|
| 542 |
+
# 1) Scan: which motors are online, on which channel, which ID (disabled, no motion)
|
| 543 |
+
python -m umi_infer.robot_io.gripper_tool scan
|
| 544 |
+
|
| 545 |
+
# 2) Passive read: move the jaws by hand and watch the angle -> channel/ID/codec OK
|
| 546 |
+
python -m umi_infer.robot_io.gripper_tool read --motor 0:8 --motor 1:8 # 0=CAN1 left, 1=CAN2 right
|
| 547 |
+
|
| 548 |
+
# 3) Small test move on the left gripper: -15 deg from current position, gentle
|
| 549 |
+
python -m umi_infer.robot_io.gripper_tool goto --motor 0:8 --delta-deg -15 --kp 8 --lead-deg 4 --yes
|
| 550 |
+
|
| 551 |
+
# 4) Sweep full travel (auto-reverse at stops), both grippers
|
| 552 |
+
python -m umi_infer.robot_io.gripper_tool sweep --motor 0:8 --motor 1:8 --yes
|
| 553 |
+
|
| 554 |
+
# 5) Recalibrate: hit each end twice, write data/gripper_calib.json
|
| 555 |
+
python -m umi_infer.robot_io.gripper_tool calib --motor 0:8 --motor 1:8 --yes
|
| 556 |
+
|
| 557 |
+
Optional udev rule to avoid sudo (run once as root, your user must be in plugdev):
|
| 558 |
+
echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="0053", MODE="0660", GROUP="plugdev"' \\
|
| 559 |
+
| sudo tee /etc/udev/rules.d/99-canalystii.rules
|
| 560 |
+
sudo udevadm control --reload-rules && sudo udevadm trigger
|
| 561 |
+
(then replug the CAN box)
|
| 562 |
+
"""
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def main(argv=None):
|
| 566 |
+
ap = argparse.ArgumentParser(
|
| 567 |
+
description="Standalone gripper motor CAN tool (does not touch the arms)",
|
| 568 |
+
epilog=EXAMPLES, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 569 |
+
ap.add_argument("--bitrate", type=int, default=1_000_000, help="CAN bitrate (default 1 Mbit)")
|
| 570 |
+
ap.add_argument("--device", type=int, default=0, help="CANalyst device index (default 0)")
|
| 571 |
+
ap.add_argument("--rate-hz", type=float, default=200.0, help="send/control rate (default 200)")
|
| 572 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 573 |
+
|
| 574 |
+
ps = sub.add_parser("scan", help="scan channels x IDs for online motors (disabled, no motion)")
|
| 575 |
+
ps.add_argument("--channels", type=int, nargs="+", default=[0, 1])
|
| 576 |
+
ps.add_argument("--id-min", type=lambda x: int(x, 0), default=0x01)
|
| 577 |
+
ps.add_argument("--id-max", type=lambda x: int(x, 0), default=0x0E)
|
| 578 |
+
ps.add_argument("--dwell", type=float, default=0.12, help="query time per ID (s)")
|
| 579 |
+
ps.set_defaults(func=cmd_scan)
|
| 580 |
+
|
| 581 |
+
pr = sub.add_parser("read", help="passive angle read (disabled, movable by hand)")
|
| 582 |
+
pr.add_argument("--motor", type=parse_motor, action="append", required=True,
|
| 583 |
+
help="channel:cmd_id[:fb_id], repeatable")
|
| 584 |
+
pr.add_argument("--seconds", type=float, default=0, help="duration, 0 = until Ctrl-C")
|
| 585 |
+
pr.set_defaults(func=cmd_read)
|
| 586 |
+
|
| 587 |
+
def _active(p):
|
| 588 |
+
p.add_argument("--motor", type=parse_motor, action="append", required=True,
|
| 589 |
+
help="channel:cmd_id[:fb_id], repeatable")
|
| 590 |
+
p.add_argument("--yes", action="store_true", help="confirm actually driving the grippers")
|
| 591 |
+
p.add_argument("--kp", type=float, default=5.0, help="MIT position gain (default 5; raise if it does not move)")
|
| 592 |
+
p.add_argument("--kd", type=float, default=0.5, help="MIT damping gain (default 0.5)")
|
| 593 |
+
p.add_argument("--lead-deg", type=float, default=3.0,
|
| 594 |
+
help="max target lead over measured, deg -> max force ~= kp*rad(lead) (default 3 -> 0.26 Nm)")
|
| 595 |
+
p.add_argument("--speed-deg", type=float, default=15.0, help="target speed deg/s (default 15)")
|
| 596 |
+
p.add_argument("--stall-time", type=float, default=0.5, help="blocked time that counts as a stop (default 0.5s)")
|
| 597 |
+
p.add_argument("--progress-deg", type=float, default=1.0,
|
| 598 |
+
help="min net motion still counted as moving (deg, default 1)")
|
| 599 |
+
p.add_argument("--timeout", type=float, default=30.0, help="max run time s (default 30)")
|
| 600 |
+
p.add_argument("--hold", type=float, default=0.0, help="hold force for N s after finishing (default 0)")
|
| 601 |
+
|
| 602 |
+
pw = sub.add_parser("sweep", help="sweep travel, auto-reverse at stops (enables motors)")
|
| 603 |
+
_active(pw)
|
| 604 |
+
pw.add_argument("--range-deg", type=float, default=60.0,
|
| 605 |
+
help="travel cap +/- deg relative to start position (default 60)")
|
| 606 |
+
pw.add_argument("--start-dir", choices=["close", "open"], default="close",
|
| 607 |
+
help="initial direction (default close = negative)")
|
| 608 |
+
pw.add_argument("--reversals", type=int, default=0, help="stop after N reversals, 0 = forever")
|
| 609 |
+
pw.set_defaults(func=cmd_sweep)
|
| 610 |
+
|
| 611 |
+
pc = sub.add_parser("calib", help="recalibrate: hit both ends at low force, write calibration json")
|
| 612 |
+
_active(pc)
|
| 613 |
+
pc.add_argument("--range-deg", type=float, default=60.0,
|
| 614 |
+
help="travel cap +/- deg relative to start position (default 60)")
|
| 615 |
+
pc.add_argument("--start-dir", choices=["close", "open"], default="close",
|
| 616 |
+
help="initial direction (default close = negative = closing)")
|
| 617 |
+
pc.add_argument("--reversals", type=int, default=4,
|
| 618 |
+
help="number of reversals; 4 = each end twice for repeatability (default 4)")
|
| 619 |
+
pc.add_argument("--open-deg", type=float, default=None,
|
| 620 |
+
help="degrees for full open (scale). Default: measured travel (opening = true motor angle); "
|
| 621 |
+
"a number maps to an external scale (e.g. 90)")
|
| 622 |
+
pc.add_argument("--spread-tol", type=float, default=2.0,
|
| 623 |
+
help="max spread between hits at one end before it is untrusted (deg, default 2)")
|
| 624 |
+
pc.add_argument("--out", default=os.path.join(os.environ.get("UMI_INFER_DATA", "data"), "gripper_calib.json"),
|
| 625 |
+
help="calibration output json")
|
| 626 |
+
# 4 reversals x ~90 deg travel @ 15 deg/s ~= 25 s; the 30 s default is too tight
|
| 627 |
+
pc.set_defaults(func=cmd_calib, timeout=90.0)
|
| 628 |
+
|
| 629 |
+
pg = sub.add_parser("goto", help="move by a relative angle from current position (enables motors)")
|
| 630 |
+
_active(pg)
|
| 631 |
+
pg.add_argument("--delta-deg", type=float, required=True, help="relative move in deg")
|
| 632 |
+
pg.add_argument("--tol-deg", type=float, default=1.0, help="arrival tolerance (default 1 deg)")
|
| 633 |
+
pg.set_defaults(func=cmd_goto)
|
| 634 |
+
|
| 635 |
+
pr2 = sub.add_parser("recompute", help="recompute the scale in a calibration json, no hardware")
|
| 636 |
+
pr2.add_argument("--file", default=os.path.join(os.environ.get("UMI_INFER_DATA", "data"), "gripper_calib.json"))
|
| 637 |
+
pr2.add_argument("--out", default=None, help="default: overwrite in place")
|
| 638 |
+
pr2.add_argument("--open-deg", type=float, default=None,
|
| 639 |
+
help="degrees for full open; default: measured travel")
|
| 640 |
+
pr2.set_defaults(func=cmd_recompute)
|
| 641 |
+
|
| 642 |
+
args = ap.parse_args(argv)
|
| 643 |
+
return args.func(args)
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
if __name__ == "__main__":
|
| 647 |
+
sys.exit(main())
|
flexiv-umi-infer/umi_infer/robot_io/insta_live.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-time Insta360 X4 Air -> latest cropped/scaled RGB frame for live policy observations.
|
| 2 |
+
|
| 3 |
+
Each InstaLiveCamera runs a persistent `insta360_cli stream` whose idx0 dual-fisheye
|
| 4 |
+
H.264 is redirected (INSTA360_VIDEO0_PATH) into a fifo, piped through ffmpeg which
|
| 5 |
+
crops ONE fisheye half (the dual-fisheye frame is 1920x960 = two 960x960 lenses
|
| 6 |
+
side by side) and scales it to out_size, emitting raw rgb24 on stdout. A reader
|
| 7 |
+
thread keeps the most recent frame.
|
| 8 |
+
|
| 9 |
+
Default out_size is 960 (native half, no resize): training images are raw 960x960
|
| 10 |
+
fisheye halves and the policy resizes them itself, so this matches the training
|
| 11 |
+
preprocessing chain pixel for pixel.
|
| 12 |
+
|
| 13 |
+
Camera serials and halves come from robot_io/cam_ids.py (env INSTA360_LEFT_SN /
|
| 14 |
+
INSTA360_RIGHT_SN / INSTA360_LEFT_HALF / INSTA360_RIGHT_HALF). The half must be the one
|
| 15 |
+
the hand-eye extrinsic was calibrated on; images and extrinsics must change together.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import signal
|
| 22 |
+
import subprocess
|
| 23 |
+
import threading
|
| 24 |
+
import time
|
| 25 |
+
from typing import Optional, Tuple
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
log = logging.getLogger("umi_infer.insta_live")
|
| 30 |
+
|
| 31 |
+
# Patched Insta360 CameraSDK CLI (build it from tools/insta360_cli_dual.cc, see tools/README.md).
|
| 32 |
+
CLI = os.environ.get("INSTA360_CLI", os.path.join(
|
| 33 |
+
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
| 34 |
+
"tools", "insta360_cli_dual"))
|
| 35 |
+
|
| 36 |
+
# One SDK service port per camera process; they must differ or the second camera is not found.
|
| 37 |
+
CAM_SERVICE_PORT = {"left": 9701, "right": 9702}
|
| 38 |
+
# Directory with the CameraSDK shared libraries (libCameraSDK.so ...), prepended to LD_LIBRARY_PATH.
|
| 39 |
+
SDK_LIB = os.environ.get("INSTA360_SDK_LIB", "")
|
| 40 |
+
|
| 41 |
+
HALF = 960 # each fisheye lens is 960x960 within the 1920x960 dual frame
|
| 42 |
+
NATIVE = HALF # out_size == NATIVE means no resize (same size as training images)
|
| 43 |
+
|
| 44 |
+
# ffmpeg binary: env FLEXIV_FFMPEG (e.g. one that lives only in a conda env/bin), else PATH.
|
| 45 |
+
FFMPEG = os.environ.get("FLEXIV_FFMPEG", "")
|
| 46 |
+
if not FFMPEG:
|
| 47 |
+
from shutil import which as _which
|
| 48 |
+
FFMPEG = _which("ffmpeg") or "ffmpeg"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def kill_stale_cameras(want_serials=(), reason: str = "") -> bool:
|
| 52 |
+
"""Kill leftover insta360_cli processes, wait for USB release, then verify via discover.
|
| 53 |
+
|
| 54 |
+
CameraSDK often crashes during teardown and leaves orphans holding the USB channel; the
|
| 55 |
+
next start then fails with `serial_not_found`. The kernel needs ~6 s to release USB, and
|
| 56 |
+
pkill + sleep alone is not always enough, so we only succeed once discover lists every
|
| 57 |
+
wanted serial. Idempotent: with no leftovers it costs one discover call.
|
| 58 |
+
"""
|
| 59 |
+
import glob
|
| 60 |
+
import json as _json
|
| 61 |
+
import signal
|
| 62 |
+
import subprocess
|
| 63 |
+
|
| 64 |
+
def _pids():
|
| 65 |
+
out = set()
|
| 66 |
+
for pat in ("insta360_cli",):
|
| 67 |
+
try:
|
| 68 |
+
r = subprocess.run(["pgrep", "-f", pat], capture_output=True, text=True)
|
| 69 |
+
out |= {int(x) for x in (r.stdout or "").split() if x.isdigit()}
|
| 70 |
+
except Exception: # noqa: BLE001
|
| 71 |
+
pass
|
| 72 |
+
out.discard(os.getpid())
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
n0 = len(_pids())
|
| 76 |
+
if n0:
|
| 77 |
+
log.warning("Found %d leftover camera processes%s, cleaning up ...", n0,
|
| 78 |
+
(" [" + reason + "]") if reason else "")
|
| 79 |
+
for sig, wait in ((signal.SIGTERM, 1.5), (signal.SIGTERM, 1.5), (signal.SIGKILL, 1.0)):
|
| 80 |
+
cur = _pids()
|
| 81 |
+
if not cur:
|
| 82 |
+
break
|
| 83 |
+
for pid in cur:
|
| 84 |
+
try: # kill the process group: the CLI runs under setsid, children would survive
|
| 85 |
+
os.killpg(os.getpgid(pid), sig)
|
| 86 |
+
except Exception: # noqa: BLE001
|
| 87 |
+
try:
|
| 88 |
+
os.kill(pid, sig)
|
| 89 |
+
except Exception: # noqa: BLE001
|
| 90 |
+
pass
|
| 91 |
+
time.sleep(wait)
|
| 92 |
+
for f in glob.glob("/tmp/insta_*.h264.fifo"):
|
| 93 |
+
try:
|
| 94 |
+
os.unlink(f)
|
| 95 |
+
except OSError:
|
| 96 |
+
pass
|
| 97 |
+
if n0:
|
| 98 |
+
log.warning(" waiting 6s for the kernel to release USB ...")
|
| 99 |
+
time.sleep(6.0)
|
| 100 |
+
|
| 101 |
+
want = set(want_serials or ())
|
| 102 |
+
if not want:
|
| 103 |
+
return True
|
| 104 |
+
env = dict(os.environ)
|
| 105 |
+
env["LD_LIBRARY_PATH"] = SDK_LIB + ":" + env.get("LD_LIBRARY_PATH", "")
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
while True:
|
| 108 |
+
seen = set()
|
| 109 |
+
try:
|
| 110 |
+
r = subprocess.run([CLI, "discover"], capture_output=True, text=True,
|
| 111 |
+
timeout=20, env=env, cwd=os.path.dirname(CLI))
|
| 112 |
+
seen = {d.get("serial")
|
| 113 |
+
for d in _json.loads(r.stdout or "{}").get("devices", [])}
|
| 114 |
+
except Exception as e: # noqa: BLE001
|
| 115 |
+
log.warning(" discover failed: %s", repr(e)[:80])
|
| 116 |
+
if want <= seen:
|
| 117 |
+
log.info("Cameras visible (discover): %s", sorted(seen & want))
|
| 118 |
+
return True
|
| 119 |
+
if time.time() - t0 > 30.0:
|
| 120 |
+
log.error("WARNING: discover only sees %s, missing %s; not a leftover process. "
|
| 121 |
+
"Check: camera powered on / USB mode set to Android control / cable",
|
| 122 |
+
sorted(seen) or "none", sorted(want - seen))
|
| 123 |
+
return False
|
| 124 |
+
time.sleep(2.0)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _read_exact(stream, n: int) -> Optional[bytes]:
|
| 128 |
+
buf = bytearray()
|
| 129 |
+
while len(buf) < n:
|
| 130 |
+
chunk = stream.read(n - len(buf))
|
| 131 |
+
if not chunk:
|
| 132 |
+
return None
|
| 133 |
+
buf.extend(chunk)
|
| 134 |
+
return bytes(buf)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class InstaLiveCamera:
|
| 138 |
+
"""Persistent live stream from one camera (by serial) -> newest RGB frame."""
|
| 139 |
+
|
| 140 |
+
def __init__(self, serial: str, *, half: str = "left", out_size: int = 480,
|
| 141 |
+
resolution: int = 2, bitrate_kbps: int = 512,
|
| 142 |
+
stream_seconds: int = 86400, service_port: int = 0,
|
| 143 |
+
cli: str = CLI, sdk_lib: str = SDK_LIB, pix_fmt: str = "rgb24"):
|
| 144 |
+
assert half in ("left", "right"), half
|
| 145 |
+
# yuv420p = raw decoded planes, no color conversion here (the policy side converts
|
| 146 |
+
# with the same call used in training)
|
| 147 |
+
assert pix_fmt in ("rgb24", "yuv420p"), pix_fmt
|
| 148 |
+
assert pix_fmt == "rgb24" or out_size == HALF, "yuv420p only supports the native half, no resize"
|
| 149 |
+
self.pix_fmt = pix_fmt
|
| 150 |
+
self.serial = serial
|
| 151 |
+
self.service_port = int(service_port)
|
| 152 |
+
self.half = half
|
| 153 |
+
self.out_size = int(out_size)
|
| 154 |
+
self.resolution = resolution
|
| 155 |
+
self.bitrate_kbps = bitrate_kbps
|
| 156 |
+
self.stream_seconds = stream_seconds
|
| 157 |
+
self.cli = cli
|
| 158 |
+
self.sdk_lib = sdk_lib
|
| 159 |
+
self.fifo = f"/tmp/insta_{serial}.h264.fifo"
|
| 160 |
+
|
| 161 |
+
self._proc_cli: Optional[subprocess.Popen] = None
|
| 162 |
+
self._proc_ff: Optional[subprocess.Popen] = None
|
| 163 |
+
self._reader: Optional[threading.Thread] = None
|
| 164 |
+
self._stop = threading.Event()
|
| 165 |
+
self._lock = threading.Lock()
|
| 166 |
+
self._latest: Optional[np.ndarray] = None
|
| 167 |
+
self._stamp: float = 0.0
|
| 168 |
+
self._nframes = 0
|
| 169 |
+
|
| 170 |
+
def start(self) -> None:
|
| 171 |
+
try:
|
| 172 |
+
os.remove(self.fifo)
|
| 173 |
+
except FileNotFoundError:
|
| 174 |
+
pass
|
| 175 |
+
os.mkfifo(self.fifo)
|
| 176 |
+
|
| 177 |
+
env = dict(os.environ)
|
| 178 |
+
env["LD_LIBRARY_PATH"] = self.sdk_lib + ":" + env.get("LD_LIBRARY_PATH", "")
|
| 179 |
+
|
| 180 |
+
x = 0 if self.half == "left" else HALF
|
| 181 |
+
# No scale filter at out_size == 960 (native half): a 960->960 resample only blurs,
|
| 182 |
+
# and training images are raw 960 halves.
|
| 183 |
+
vf = f"crop={HALF}:{HALF}:{x}:0"
|
| 184 |
+
if self.out_size != HALF:
|
| 185 |
+
vf += f",scale={self.out_size}:{self.out_size}:flags=area"
|
| 186 |
+
ff_argv = [FFMPEG, "-nostdin", "-hide_banner", "-loglevel", "error",
|
| 187 |
+
"-fflags", "nobuffer", "-flags", "low_delay",
|
| 188 |
+
"-f", "h264", "-i", self.fifo,
|
| 189 |
+
"-vf", vf, "-f", "rawvideo", "-pix_fmt", self.pix_fmt, "-"]
|
| 190 |
+
self._proc_ff = subprocess.Popen(
|
| 191 |
+
ff_argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
|
| 192 |
+
stdin=subprocess.DEVNULL) # no terminal stdin: ffmpeg would eat keystrokes as commands
|
| 193 |
+
|
| 194 |
+
# ffmpeg must open the fifo read end before the writer opens the write end.
|
| 195 |
+
time.sleep(0.3)
|
| 196 |
+
|
| 197 |
+
env_cli = dict(env)
|
| 198 |
+
env_cli["INSTA360_VIDEO0_PATH"] = self.fifo
|
| 199 |
+
cli_argv = [self.cli, f"--serial={self.serial}"]
|
| 200 |
+
if self.service_port > 0:
|
| 201 |
+
cli_argv.append(f"--service-port={self.service_port}")
|
| 202 |
+
cli_argv += ["stream", str(self.stream_seconds), str(self.resolution), "1",
|
| 203 |
+
str(self.bitrate_kbps), "0", "1", "0"]
|
| 204 |
+
self._proc_cli = subprocess.Popen(
|
| 205 |
+
cli_argv, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
| 206 |
+
env=env_cli, preexec_fn=os.setsid, stdin=subprocess.DEVNULL)
|
| 207 |
+
|
| 208 |
+
self._reader = threading.Thread(target=self._read_loop, daemon=True)
|
| 209 |
+
self._reader.start()
|
| 210 |
+
log.info("InstaLiveCamera %s (half=%s, %dpx) started", self.serial, self.half, self.out_size)
|
| 211 |
+
|
| 212 |
+
def _read_loop(self) -> None:
|
| 213 |
+
s = self.out_size
|
| 214 |
+
shape = (s, s, 3) if self.pix_fmt == "rgb24" else (s * 3 // 2, s) # I420: Y followed by U, V
|
| 215 |
+
nbytes = shape[0] * shape[1] * (3 if self.pix_fmt == "rgb24" else 1)
|
| 216 |
+
stdout = self._proc_ff.stdout
|
| 217 |
+
while not self._stop.is_set():
|
| 218 |
+
buf = _read_exact(stdout, nbytes)
|
| 219 |
+
if buf is None:
|
| 220 |
+
log.warning("InstaLiveCamera %s: ffmpeg stream ended", self.serial)
|
| 221 |
+
break
|
| 222 |
+
frame = np.frombuffer(buf, np.uint8).reshape(shape)
|
| 223 |
+
with self._lock:
|
| 224 |
+
self._latest = frame
|
| 225 |
+
self._stamp = time.time()
|
| 226 |
+
self._nframes += 1
|
| 227 |
+
|
| 228 |
+
def get_frame(self) -> Tuple[Optional[np.ndarray], float]:
|
| 229 |
+
"""Return (frame copy, capture_stamp) or (None, 0.0).
|
| 230 |
+
|
| 231 |
+
rgb24: HxWx3; yuv420p: (H*3/2)xW I420 planes."""
|
| 232 |
+
with self._lock:
|
| 233 |
+
if self._latest is None:
|
| 234 |
+
return None, 0.0
|
| 235 |
+
return self._latest.copy(), self._stamp
|
| 236 |
+
|
| 237 |
+
def wait_ready(self, timeout_s: float = 30.0) -> bool:
|
| 238 |
+
t0 = time.time()
|
| 239 |
+
while time.time() - t0 < timeout_s:
|
| 240 |
+
with self._lock:
|
| 241 |
+
if self._latest is not None:
|
| 242 |
+
return True
|
| 243 |
+
if self._proc_cli and self._proc_cli.poll() is not None:
|
| 244 |
+
err = ""
|
| 245 |
+
if self._proc_cli.stderr:
|
| 246 |
+
try:
|
| 247 |
+
err = self._proc_cli.stderr.read().decode(errors="replace")[-400:]
|
| 248 |
+
except Exception:
|
| 249 |
+
pass
|
| 250 |
+
log.error("InstaLiveCamera %s: cli exited early rc=%s %s",
|
| 251 |
+
self.serial, self._proc_cli.returncode, err)
|
| 252 |
+
return False
|
| 253 |
+
time.sleep(0.2)
|
| 254 |
+
return False
|
| 255 |
+
|
| 256 |
+
def fps(self) -> float:
|
| 257 |
+
with self._lock:
|
| 258 |
+
return float(self._nframes)
|
| 259 |
+
|
| 260 |
+
def stop(self) -> None:
|
| 261 |
+
self._stop.set()
|
| 262 |
+
if self._proc_cli and self._proc_cli.poll() is None:
|
| 263 |
+
try:
|
| 264 |
+
os.killpg(os.getpgid(self._proc_cli.pid), signal.SIGTERM)
|
| 265 |
+
self._proc_cli.wait(timeout=3)
|
| 266 |
+
except Exception:
|
| 267 |
+
try:
|
| 268 |
+
self._proc_cli.kill()
|
| 269 |
+
except Exception:
|
| 270 |
+
pass
|
| 271 |
+
if self._proc_ff and self._proc_ff.poll() is None:
|
| 272 |
+
try:
|
| 273 |
+
self._proc_ff.terminate()
|
| 274 |
+
self._proc_ff.wait(timeout=3)
|
| 275 |
+
except Exception:
|
| 276 |
+
try:
|
| 277 |
+
self._proc_ff.kill()
|
| 278 |
+
except Exception:
|
| 279 |
+
pass
|
| 280 |
+
try:
|
| 281 |
+
os.remove(self.fifo)
|
| 282 |
+
except FileNotFoundError:
|
| 283 |
+
pass
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class InstaDualCamera:
|
| 287 |
+
"""Two cameras = two independent InstaLiveCamera processes, each with its own service port.
|
| 288 |
+
|
| 289 |
+
The SDK has no ready-made way to drive two cameras from one process; two processes with
|
| 290 |
+
different --service-port values (9701/9702) stream both at 960x960.
|
| 291 |
+
API: get_frame(side) / wait_ready / fps(side) / stop.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def __init__(self, serials, halves, *, out_size=NATIVE, resolution=2,
|
| 295 |
+
bitrate_kbps=512, stream_seconds=86400, cli=CLI, sdk_lib=SDK_LIB,
|
| 296 |
+
service_ports=None, pix_fmt="rgb24"):
|
| 297 |
+
self.serials = dict(serials)
|
| 298 |
+
self.halves = dict(halves)
|
| 299 |
+
self.out_size = int(out_size)
|
| 300 |
+
self.sides = list(serials.keys())
|
| 301 |
+
ports = dict(service_ports or CAM_SERVICE_PORT)
|
| 302 |
+
self.cams = {
|
| 303 |
+
s: InstaLiveCamera(serials[s], half=halves[s], out_size=out_size,
|
| 304 |
+
resolution=resolution, bitrate_kbps=bitrate_kbps,
|
| 305 |
+
stream_seconds=stream_seconds,
|
| 306 |
+
service_port=int(ports.get(s, 0)), cli=cli, sdk_lib=sdk_lib,
|
| 307 |
+
pix_fmt=pix_fmt)
|
| 308 |
+
for s in self.sides}
|
| 309 |
+
self._ports = ports
|
| 310 |
+
|
| 311 |
+
def start(self):
|
| 312 |
+
# Clean up leftovers and confirm cameras are visible; otherwise serial_not_found
|
| 313 |
+
# shows up intermittently (see kill_stale_cameras).
|
| 314 |
+
kill_stale_cameras(self.serials.values(), "InstaDualCamera.start")
|
| 315 |
+
# Start one at a time with a gap: concurrent SDK init fails with serial_not_found more often.
|
| 316 |
+
for k, s in enumerate(self.sides):
|
| 317 |
+
if k:
|
| 318 |
+
time.sleep(2.0)
|
| 319 |
+
self.cams[s].start()
|
| 320 |
+
log.info("InstaDualCamera started: %s (service ports %s, half %s, %dpx)",
|
| 321 |
+
self.serials, self._ports, self.halves, self.out_size)
|
| 322 |
+
|
| 323 |
+
def get_frame(self, side):
|
| 324 |
+
return self.cams[side].get_frame()
|
| 325 |
+
|
| 326 |
+
def wait_ready(self, timeout_s=60.0):
|
| 327 |
+
t0 = time.time()
|
| 328 |
+
pending = set(self.sides)
|
| 329 |
+
while pending and time.time() - t0 < timeout_s:
|
| 330 |
+
for s in list(pending):
|
| 331 |
+
left = timeout_s - (time.time() - t0)
|
| 332 |
+
if left <= 0:
|
| 333 |
+
break
|
| 334 |
+
if self.cams[s].wait_ready(min(2.0, left)):
|
| 335 |
+
pending.discard(s)
|
| 336 |
+
log.info(" camera ready: %s (%s)", s, self.serials[s])
|
| 337 |
+
if pending:
|
| 338 |
+
log.error("Cameras not ready: %s", sorted(pending))
|
| 339 |
+
return False
|
| 340 |
+
return True
|
| 341 |
+
|
| 342 |
+
def fps(self, side):
|
| 343 |
+
return self.cams[side].fps()
|
| 344 |
+
|
| 345 |
+
def stop(self):
|
| 346 |
+
for s in self.sides:
|
| 347 |
+
try:
|
| 348 |
+
self.cams[s].stop()
|
| 349 |
+
except Exception: # noqa: BLE001
|
| 350 |
+
pass
|
flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""Flexiv kinematics: FK via yourdfpy on the URDF, IK via vendor flexivrdk.Model.reachable.
|
| 4 |
+
|
| 5 |
+
FK does not use the vendor `Model.T()`: its Python binding fails with
|
| 6 |
+
`TypeError: Unregistered type` (Eigen::Transform; flexivrdk 1.9.3). The URDF should carry
|
| 7 |
+
kinematic parameters synced from the robot (SyncKinematicsYAML), i.e. the same numbers as the vendor model.
|
| 8 |
+
|
| 9 |
+
Frame conventions (verified on hardware):
|
| 10 |
+
* URDF world == shared world of DRDK `RobotPair.states().tcp_pose` (fit: 0.11 mm / 0.011 deg).
|
| 11 |
+
* Single-arm `Robot.states().tcp_pose` is in that arm's own base frame, which differs from
|
| 12 |
+
world by a pure translation (0, -/+0.25, 0). Do not compare against URDF `base_link` (90 deg off).
|
| 13 |
+
* Vendor IK is built from a single-arm Robot and takes flange poses in that arm's base frame.
|
| 14 |
+
|
| 15 |
+
Each construction runs a round-trip self-test (camera pose -> flange -> arm base -> reachable -> seed q).
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
from scipy.spatial.transform import Rotation as Rot
|
| 25 |
+
|
| 26 |
+
# Site identity. Set these for your cell (see README "Configuration").
|
| 27 |
+
# Default: the bundled dual-arm URDF (nominal Flexiv kinematics, gripper frames without meshes).
|
| 28 |
+
URDF = os.environ.get("FLEXIV_URDF", os.path.join(
|
| 29 |
+
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
| 30 |
+
"urdf", "flexiv_rizon4_dual_umi.urdf"))
|
| 31 |
+
SN = {"left": os.environ.get("FLEXIV_LEFT_SN", ""), "right": os.environ.get("FLEXIV_RIGHT_SN", "")}
|
| 32 |
+
# Joint/link name prefix of each arm in the URDF ("left_" / "right_" in the bundled one).
|
| 33 |
+
def prefix(side, sn):
|
| 34 |
+
return os.environ.get("FLEXIV_URDF_PREFIX_" + side.upper(), "%s_" % side)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
PRE = {s: prefix(s, SN[s]) for s in SN}
|
| 38 |
+
# Directory holding per-cell data: anchor.json, gripper_calib.json, E_left.npy, E_right.npy, E_from_urdf.json.
|
| 39 |
+
DATA_DIR = os.environ.get("UMI_INFER_DATA", os.path.join(
|
| 40 |
+
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "data"))
|
| 41 |
+
CAM_LINK = "grip_camera_optical_frame"
|
| 42 |
+
# Hardware joint limits from robot info() (5 deg tighter than the URDF).
|
| 43 |
+
RQMIN = np.array([-160., -130., -170., -107., -170., -80., -170.])
|
| 44 |
+
RQMAX = np.array([160., 130., 170., 154., 170., 260., 170.])
|
| 45 |
+
_URDF_CACHE = {}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_urdf(path=URDF):
|
| 49 |
+
try:
|
| 50 |
+
import yourdfpy
|
| 51 |
+
except ImportError as exc:
|
| 52 |
+
raise ImportError("URDF FK requires the robot extra: pip install -e .[robot]") from exc
|
| 53 |
+
if not path:
|
| 54 |
+
raise ValueError("no URDF: pass --urdf or set FLEXIV_URDF")
|
| 55 |
+
if path not in _URDF_CACHE:
|
| 56 |
+
_URDF_CACHE[path] = yourdfpy.URDF.load(path, load_meshes=False,
|
| 57 |
+
build_scene_graph=True)
|
| 58 |
+
return _URDF_CACHE[path]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def pose7_to_T(p):
|
| 62 |
+
"""[x,y,z,qw,qx,qy,qz] -> 4x4 (Flexiv RDK pose order)."""
|
| 63 |
+
p = np.asarray(p, float)
|
| 64 |
+
w, x, y, z = p[3:7] / np.linalg.norm(p[3:7])
|
| 65 |
+
T = np.eye(4)
|
| 66 |
+
T[:3, :3] = Rot.from_quat([x, y, z, w]).as_matrix()
|
| 67 |
+
T[:3, 3] = p[:3]
|
| 68 |
+
return T
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def T_to_pose7(T):
|
| 72 |
+
q = Rot.from_matrix(np.asarray(T)[:3, :3]).as_quat() # xyzw
|
| 73 |
+
return list(np.asarray(T)[:3, 3]) + [q[3], q[0], q[1], q[2]]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def ang_between(Ra, Rb):
|
| 77 |
+
c = (np.trace(np.asarray(Ra).T @ np.asarray(Rb)) - 1.0) / 2.0
|
| 78 |
+
return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def limit_margin(q_deg):
|
| 82 |
+
"""Margin to hardware joint limits (deg); negative if out of range."""
|
| 83 |
+
d = np.asarray(q_deg, float)
|
| 84 |
+
return float(min(np.min(d - RQMIN), np.min(RQMAX - d)))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Arm:
|
| 88 |
+
"""FK/IK for one arm. robot=False gives FK only (no connection, no IK)."""
|
| 89 |
+
|
| 90 |
+
def __init__(self, side, urdf=URDF, robot=True, bridge_json=None, verbose=True, pre=None):
|
| 91 |
+
if side not in SN:
|
| 92 |
+
raise ValueError("side must be left/right")
|
| 93 |
+
self.side, self.pre, self.verbose = side, pre or PRE[side], verbose
|
| 94 |
+
self.U = load_urdf(urdf)
|
| 95 |
+
self.urdf = urdf
|
| 96 |
+
self.r = self.m = None
|
| 97 |
+
self.B = None # T_world_sdkbase
|
| 98 |
+
self.q_now = None
|
| 99 |
+
if bridge_json and os.path.exists(bridge_json):
|
| 100 |
+
with open(bridge_json) as f:
|
| 101 |
+
self.B = np.asarray(json.load(f)[side]["T_world_sdkbase"], float)
|
| 102 |
+
self._say("bridge loaded from cache %s" % bridge_json)
|
| 103 |
+
if robot:
|
| 104 |
+
self._connect()
|
| 105 |
+
if self.B is None:
|
| 106 |
+
self._measure_bridge()
|
| 107 |
+
self.selftest()
|
| 108 |
+
|
| 109 |
+
# ---------- internal ----------
|
| 110 |
+
def _say(self, msg):
|
| 111 |
+
if self.verbose:
|
| 112 |
+
print("[kin %s] %s" % (self.side, msg), flush=True)
|
| 113 |
+
|
| 114 |
+
def _connect(self):
|
| 115 |
+
import flexivrdk
|
| 116 |
+
self.r = flexivrdk.Robot(SN[self.side])
|
| 117 |
+
self.m = flexivrdk.Model(self.r)
|
| 118 |
+
st = self.r.states()
|
| 119 |
+
self.q_now = np.asarray(st.q, float)
|
| 120 |
+
self.tcp_now = np.asarray(st.tcp_pose, float)
|
| 121 |
+
self._say("connected %s, current q (deg) %s"
|
| 122 |
+
% (SN[self.side], np.round(np.degrees(self.q_now), 2).tolist()))
|
| 123 |
+
|
| 124 |
+
def _measure_bridge(self):
|
| 125 |
+
"""Measure T_world_sdkbase from FK at current q and the single-arm tcp_pose."""
|
| 126 |
+
T_w_f = self.fk(self.q_now, "flange")
|
| 127 |
+
self.B = T_w_f @ np.linalg.inv(pose7_to_T(self.tcp_now))
|
| 128 |
+
rv = Rot.from_matrix(self.B[:3, :3]).as_rotvec()
|
| 129 |
+
self._say("world<-arm base: translation %s m, rotation %.4f deg (expect ~pure translation (0,-/+0.25,0))"
|
| 130 |
+
% (np.round(self.B[:3, 3], 6).tolist(), np.degrees(np.linalg.norm(rv))))
|
| 131 |
+
if np.degrees(np.linalg.norm(rv)) > 0.5:
|
| 132 |
+
raise RuntimeError("bridge rotation %.3f deg is too large; frame convention changed, check setup"
|
| 133 |
+
% np.degrees(np.linalg.norm(rv)))
|
| 134 |
+
|
| 135 |
+
# ---------- FK ----------
|
| 136 |
+
def fk(self, q_rad, link="flange"):
|
| 137 |
+
"""Joint angles (rad) -> 4x4 pose of link in URDF world."""
|
| 138 |
+
q = np.asarray(q_rad, float)
|
| 139 |
+
self.U.update_cfg({self.pre + "joint%d" % k: float(q[k - 1]) for k in range(1, 8)})
|
| 140 |
+
return np.asarray(self.U.get_transform(self.pre + link, "world"), float)
|
| 141 |
+
|
| 142 |
+
def fk_cam(self, q_rad):
|
| 143 |
+
return self.fk(q_rad, CAM_LINK)
|
| 144 |
+
|
| 145 |
+
def T_flange_cam(self, q_rad=None):
|
| 146 |
+
"""Fixed flange->camera transform (URDF/CAD); independent of q."""
|
| 147 |
+
q = np.zeros(7) if q_rad is None else q_rad
|
| 148 |
+
return np.linalg.inv(self.fk(q, "flange")) @ self.fk(q, CAM_LINK)
|
| 149 |
+
|
| 150 |
+
# ---------- IK (vendor) ----------
|
| 151 |
+
def ik_flange(self, T_world_flange, seed_q_rad, free_orientation=False):
|
| 152 |
+
"""Vendor reachable(). Input: flange pose in world. Returns (q, reachable)."""
|
| 153 |
+
if self.m is None:
|
| 154 |
+
raise RuntimeError("not connected to robot, no IK")
|
| 155 |
+
T_sdk = np.linalg.inv(self.B) @ np.asarray(T_world_flange, float)
|
| 156 |
+
ok, sol = self.m.reachable(T_to_pose7(T_sdk), list(np.asarray(seed_q_rad, float)),
|
| 157 |
+
bool(free_orientation))
|
| 158 |
+
return (np.asarray(sol, float) if ok else None), bool(ok)
|
| 159 |
+
|
| 160 |
+
def ik_cam(self, T_world_cam, seed_q_rad, free_orientation=False):
|
| 161 |
+
"""Solve for a camera optical-frame pose. Returns (q, pos_err_mm, rot_err_deg) or None.
|
| 162 |
+
|
| 163 |
+
Vendor IK solves the flange; the camera pose is converted to a flange pose, and the
|
| 164 |
+
result is re-checked with FK to report the actual error.
|
| 165 |
+
"""
|
| 166 |
+
T_world_cam = np.asarray(T_world_cam, float)
|
| 167 |
+
X = self.T_flange_cam()
|
| 168 |
+
q, ok = self.ik_flange(T_world_cam @ np.linalg.inv(X), seed_q_rad,
|
| 169 |
+
free_orientation)
|
| 170 |
+
if not ok:
|
| 171 |
+
return None
|
| 172 |
+
T_got = self.fk_cam(q)
|
| 173 |
+
pe = float(np.linalg.norm(T_got[:3, 3] - T_world_cam[:3, 3]) * 1000)
|
| 174 |
+
ae = ang_between(T_got[:3, :3], T_world_cam[:3, :3])
|
| 175 |
+
return q, pe, ae
|
| 176 |
+
|
| 177 |
+
# ---------- self-test ----------
|
| 178 |
+
def selftest(self, tol_deg=0.6):
|
| 179 |
+
"""Round trip: camera pose at current q -> IK -> should return current q."""
|
| 180 |
+
got = self.ik_cam(self.fk_cam(self.q_now), self.q_now)
|
| 181 |
+
if got is None:
|
| 182 |
+
raise RuntimeError("self-test failed: current pose is not solvable; bridge or frame error")
|
| 183 |
+
q, pe, ae = got
|
| 184 |
+
d = float(np.abs(np.degrees(q - self.q_now)).max())
|
| 185 |
+
self._say("self-test round trip: max joint diff %.4f deg, cam pos diff %.3f mm, rot diff %.4f deg" % (d, pe, ae))
|
| 186 |
+
if d > tol_deg:
|
| 187 |
+
m = limit_margin(np.degrees(self.q_now))
|
| 188 |
+
extra = " (joint-limit margin is only %.2f deg; near a limit IK can only back off)" % m if m < 1 else ""
|
| 189 |
+
raise RuntimeError("self-test round-trip joint diff %.3f deg > %.1f deg%s" % (d, tol_deg, extra))
|
| 190 |
+
return d
|
| 191 |
+
|
| 192 |
+
def close(self):
|
| 193 |
+
self.m = None
|
| 194 |
+
self.r = None
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def measure_bridges(out=None, urdf=URDF):
|
| 198 |
+
"""Measure and save bridges for both arms, for later offline FK-only use."""
|
| 199 |
+
res = {}
|
| 200 |
+
for s in ("left", "right"):
|
| 201 |
+
a = Arm(s, urdf=urdf, robot=True)
|
| 202 |
+
res[s] = {"T_world_sdkbase": a.B.tolist(),
|
| 203 |
+
"q_measured_deg": np.degrees(a.q_now).tolist(),
|
| 204 |
+
"T_flange_cam": a.T_flange_cam().tolist()}
|
| 205 |
+
a.close()
|
| 206 |
+
if out:
|
| 207 |
+
with open(out, "w") as f:
|
| 208 |
+
json.dump(res, f, indent=1, ensure_ascii=False)
|
| 209 |
+
print("bridge ->", out)
|
| 210 |
+
return res
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
import argparse
|
| 215 |
+
ap = argparse.ArgumentParser(description="FK (yourdfpy) + vendor IK (reachable) self-test")
|
| 216 |
+
ap.add_argument("--side", default=None, choices=("left", "right"))
|
| 217 |
+
ap.add_argument("--out", default="kin_bridge.json")
|
| 218 |
+
a = ap.parse_args()
|
| 219 |
+
if a.side:
|
| 220 |
+
arm = Arm(a.side)
|
| 221 |
+
X = arm.T_flange_cam()
|
| 222 |
+
print("T_flange_cam (CAD) translation mm = %s" % np.round(X[:3, 3] * 1000, 2).tolist())
|
| 223 |
+
arm.close()
|
| 224 |
+
else:
|
| 225 |
+
measure_bridges(out=a.out)
|