nablaengine 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,4 @@
1
+ """NablaEngine (package nablaengine): fused, differentiable physics kernels (one CUDA block per world) for the Unitree G1 humanoid (the mjlab
2
+ model), with an analytic adjoint and a JAX interface."""
3
+
4
+ __version__ = "1.0.2"
@@ -0,0 +1,19 @@
1
+ # Packaged fixtures
2
+
3
+ The default fixtures shipped with the `nablaengine` wheel, so that the quick start runs without a source checkout:
4
+
5
+ | Path | Content |
6
+ |---|---|
7
+ | `mjlab/g1_train.mjb`, `mjlab/g1_meta.json` | The Unitree G1 model (mjlab configuration) and its metadata, copied from `fixtures/mjlab` of the repository. |
8
+ | `mjlab/LICENSE` | The licence of the Unitree G1 description (BSD 3-Clause), from MuJoCo Menagerie. |
9
+ | `mjlab/README.md` | The model's provenance and the changes made. |
10
+ | `data/mf_s0.npz` | The benchmark corpus `mf_s0` (4096 states of this G1 model), copied from `benchmarks/data`. |
11
+
12
+ Lookup order (`nablaengine.fixtures`): `$DK_FIXTURES` / `$DK_BENCH_DATA`, then `fixtures/mjlab` / `benchmarks/data` of
13
+ a source checkout, then this copy.
14
+
15
+ The reference data of the checks (the MuJoCo Warp references, the finite-difference truth, the corpora `mf_s1` ..
16
+ `mf_s3`), the terrain models and the other robots (`fixtures/robots`) are not packaged: the checks, the scripts and
17
+ these models need a checkout of <https://github.com/sailab-ai/NablaEngine> (or `DK_FIXTURES` / `DK_BENCH_DATA`
18
+ pointing into one). NablaEngine itself is licensed under the Apache License 2.0; `LICENSE`, `NOTICE` and
19
+ `THIRD_PARTY_NOTICES.md` are in the wheel's metadata (`nablaengine-<version>.dist-info/licenses`).
Binary file
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2016-2023 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,113 @@
1
+ # The G1 model (`fixtures/mjlab`)
2
+
3
+ `g1_train.mjb` is the model the engine is written for: the Unitree G1 humanoid with a floating base and 29 hinge
4
+ joints, each driven by a position (PD) actuator, standing on a flat floor. It is built from the Unitree G1 MJX
5
+ description in [MuJoCo Menagerie](https://github.com/google-deepmind/mujoco_menagerie), with feet, contacts, joint and
6
+ actuator parameters changed after the G1 configuration of [mjlab](https://github.com/mujocolab/mjlab).
7
+
8
+ This directory is the default fixtures directory of `nablaengine.fixtures` and of the scripts (`DK_FIXTURES`
9
+ overrides it). `nablaengine.fixtures.load_model()` loads the model and checks that the engine supports it.
10
+
11
+ | File | Content |
12
+ |---|---|
13
+ | `g1_train.mjb` | The compiled model in MuJoCo's binary format, 176356 bytes, sha256 `757b0997d992073b645732a1daaeab92587f00e29691b93aa76094a3f02ef379`. |
14
+ | `g1_meta.json` | Metadata of the model (below). |
15
+ | `LICENSE` | The licence of the Unitree G1 description (BSD 3-Clause), copied verbatim from MuJoCo Menagerie. |
16
+
17
+ The other files are reference data for the checks, all computed with this model: `mjw317_mf_s0.npz` and
18
+ `mjw317_mf_s1.npz`, the outputs of one control step of native MuJoCo Warp 3.17.0 and its contacts at the input states
19
+ of the benchmark corpora `mf_s0` / `mf_s1` (`scripts/make_mjw_reference.py`), and `engine_digests.json`, the sha256
20
+ digests of the engine's forward outputs (`nablaengine.checks`).
21
+
22
+ Terrain (`docs/terrain.md`): `g1_terrain_feet.mjb` and `g1_terrain_body.mjb` are this G1 with its floor replaced by
23
+ a test terrain (stairs, a rotated box obstacle, a 41 x 41 heightfield and a ground box) and explicit pairs between the
24
+ terrain and the robot's foot geoms or every robot geom with a floor pair (the floor pairs' parameters; visual meshes
25
+ and textures dropped). `mjw317_terrain_feet.npz` is native MuJoCo Warp 3.17.0's control step of 1024 `mf_s0` states
26
+ placed on that terrain (`scripts/terrain_check.py ref --scene fixtures/mjlab/g1_terrain_feet.mjb`).
27
+
28
+ ## The model
29
+
30
+ | | |
31
+ |---|---|
32
+ | Degrees of freedom | `nq` 36, `nv` 35: a free root joint and 29 hinge joints. 31 bodies (the world included), 29 actuators. |
33
+ | Collision geometry | 34 geoms: the floor plane, 2 spheres (pelvis, head) and 31 capsules, 7 of them on each sole. No meshes, boxes or other geom types. |
34
+ | Contacts | 502 explicit contact pairs and nothing else: `contype` / `conaffinity` are 0 on every robot geom. |
35
+ | Options | Timestep 5 ms, Newton solver, pyramidal friction cones, `implicitfast` integrator, Euler damping disabled. The engine sets its own Newton iteration count. |
36
+ | Control step | 4 substeps (20 ms), the convention recorded in `g1_meta.json`. |
37
+ | Other content | 3 materials, 1 light, 1 camera, 6 sites, 14 sensors and the keyframes `home` and `knees_bent`, as in Menagerie. |
38
+
39
+ The binary format ties the file to the MuJoCo version that wrote it, `mujoco==3.17.0`:
40
+ `mujoco.MjModel.from_binary_path("fixtures/mjlab/g1_train.mjb")`.
41
+
42
+ `g1_meta.json` holds:
43
+ - `mujoco_version`: the MuJoCo version that wrote the model;
44
+ - `foot_pairs`: the indices of the 14 sole-floor contact pairs (`left_foot1_floor` ... `right_foot7_floor`), whose
45
+ friction can be set per world;
46
+ - `torso_body`: the body whose centre-of-mass offset can be set per world;
47
+ - the sizes `nq`, `nv`, `nu`, `nbody` and `npair`;
48
+ - `timestep`, `substeps_per_control_step`, `solver`, `cone` and `integrator`;
49
+ - `robot`: the name of the model variant, `"mjlab"`;
50
+ - `source`: a one-line provenance.
51
+
52
+ ## How it was derived
53
+
54
+ The source is MuJoCo Menagerie at commit
55
+ [`f3b6013629c7b94f8ee93fd977b161fa8350f9bc`](https://github.com/google-deepmind/mujoco_menagerie/tree/f3b6013629c7b94f8ee93fd977b161fa8350f9bc/unitree_g1),
56
+ file `unitree_g1/scene_mjx.xml` (the flat-floor scene, which includes `unitree_g1/g1_mjx.xml`). The steps below were
57
+ applied with MuJoCo's `MjSpec` in MuJoCo 3.17.0, and the result was written with `mujoco.mj_saveModel` (not as MJCF,
58
+ whose writer rounds numbers). Applied in this order to the Menagerie files at that commit, they reproduce
59
+ `g1_train.mjb` byte for byte (the same sha256).
60
+
61
+ 1. **Sole capsules.** The foot collision geoms of the MJX model are removed: per foot, three capsules
62
+ (`<side>_foot1_collision` ... `<side>_foot3_collision`) and a box (`<side>_foot_box_collision`). In their place,
63
+ seven capsules per sole are added to each ankle-roll link, as in mjlab's G1 (left foot first, then the right):
64
+ radius 0.01 m, `contype` / `conaffinity` 0, group 3, `condim` 3, friction (0.6, 0.005, 0.0001), named
65
+ `<side>_foot<k>_collision`. Half-lengths, positions and orientations in the ankle-roll link frame:
66
+
67
+ | k | left: half-length, position, quaternion (w, x, y, z) | right: half-length, position, quaternion (w, x, y, z) |
68
+ |---|---|---|
69
+ | 1 | 0.025005, (0.075, -0.0265, -0.025), (0.707107, -0.014139, 0.706965, 0) | 0.025, (0.075, -0.026, -0.025), (0.707107, 0, 0.707107, 0) |
70
+ | 2 | 0.0835, (0.0395, -0.018, -0.025), (0.707107, 0, -0.707107, 0) | 0.0835, (0.0395, -0.018, -0.025), (0.707107, 0, -0.707107, 0) |
71
+ | 3 | 0.091, (0.039, -0.01, -0.025), (0.707107, 0, -0.707107, 0) | 0.091, (0.039, -0.01, -0.025), (0.707107, 0, -0.707107, 0) |
72
+ | 4 | 0.093, (0.039, 0, -0.025), (0.707107, 0, -0.707107, 0) | 0.093, (0.039, 0, -0.025), (0.707107, 0, -0.707107, 0) |
73
+ | 5 | 0.091, (0.039, 0.01, -0.025), (0.707107, 0, -0.707107, 0) | 0.091, (0.039, 0.01, -0.025), (0.707107, 0, -0.707107, 0) |
74
+ | 6 | 0.0835, (0.0395, 0.018, -0.025), (0.707107, 0, -0.707107, 0) | 0.0835, (0.0395, 0.018, -0.025), (0.707107, 0, -0.707107, 0) |
75
+ | 7 | 0.025, (0.075, 0.026, -0.025), (0.707107, 0, 0.707107, 0) | 0.025, (0.075, 0.026, -0.025), (0.707107, 0, 0.707107, 0) |
76
+
77
+ 2. **Contact pairs.** Menagerie's 49 explicit pairs are removed. The new pairs give mjlab's contact set of the G1, in
78
+ which every collision geom collides with the floor and with every collision geom of another body, except on
79
+ parent-child bodies and on four excluded body pairs (the pelvis with each hip-roll link, each elbow link with the
80
+ wrist-pitch link of the same arm). It is written as 502 explicit pairs, in this order: each robot collision geom
81
+ (in geom order) with the floor, named `<side>_foot<k>_floor` for the sole capsules and `<geom>__floor` otherwise;
82
+ then every allowed pair of robot collision geoms in geom order, named `<geom1>__<geom2>`. Pair parameters:
83
+ - `condim` 3 for the floor pairs and every pair with a sole capsule, 1 for the other pairs;
84
+ - sliding friction 0.6 between two sole capsules and 1.0 otherwise, torsional 0.005, rolling 0.0001;
85
+ - on every pair, MuJoCo's default `solref` (0.02, 1) and `solimp` (0.9, 0.95, 0.001, 0.5, 2). Menagerie's
86
+ foot-floor pairs have `solref` (0.008, 1).
87
+ 3. **Visual content.** The mesh geoms (which do not collide), the mesh assets and the textures are removed. This
88
+ changes no dynamics, collision or solver quantity of the model.
89
+ 4. **Options.** The timestep is 5 ms (Menagerie's MJX model: 4 ms). The other options stay as in Menagerie's MJX
90
+ model.
91
+ 5. **Actuators.** mjlab's PD gains, from the armature of each joint (Menagerie's values, as are the torque limits):
92
+ kp = armature (2 pi 10 Hz)^2 and kd = 2 * 2 * armature (2 pi 10 Hz), a natural frequency of 10 Hz and a damping
93
+ ratio of 2 (`gainprm[0]` = kp, `biasprm[1:3]` = (-kp, -kd)).
94
+ 6. **Joint and control parameters**, set on the compiled model:
95
+ - no dof friction loss (Menagerie: 0.1 N m);
96
+ - joint-limit `solref` / `solimp` at MuJoCo's defaults as above (Menagerie: (0.008, 1) and (0, 0.99, 0.01));
97
+ - mjlab's setpoint range: each actuator's `ctrlrange` is its joint's range widened on each side by
98
+ tau_max / kp, where tau_max is the joint's actuator force limit.
99
+
100
+ ## Licences
101
+
102
+ - **Unitree G1 description** (MuJoCo Menagerie `unitree_g1`): Copyright (c) 2016-2023 HangZhou YuShu TECHNOLOGY
103
+ CO.,LTD. ("Unitree Robotics"), BSD 3-Clause License. Its full text is `LICENSE` in this directory, and it applies to
104
+ `g1_train.mjb`, a modified binary form of that description. The Menagerie repository as a whole is under
105
+ Apache-2.0, but the licence of the model directory governs this model.
106
+ - **mjlab**: Apache License 2.0, Copyright 2025, The mjlab Developers. The model takes over values of mjlab's G1
107
+ configuration (the sole capsules, the contact set, the contact and joint parameters, the PD gains and the setpoint
108
+ range). It contains no mjlab code.
109
+ - The other files of this directory are covered by the repository's licence (Apache-2.0, `LICENSE` at the repository
110
+ root). `THIRD_PARTY_NOTICES.md` at the root lists all third-party material.
111
+
112
+ Unitree Robotics, Google DeepMind and the mjlab developers do not endorse this project. Their names are used only to
113
+ identify the sources.
@@ -0,0 +1,32 @@
1
+ {
2
+ "mujoco_version": "3.17.0",
3
+ "foot_pairs": [
4
+ 5,
5
+ 6,
6
+ 7,
7
+ 8,
8
+ 9,
9
+ 10,
10
+ 11,
11
+ 16,
12
+ 17,
13
+ 18,
14
+ 19,
15
+ 20,
16
+ 21,
17
+ 22
18
+ ],
19
+ "torso_body": "torso_link",
20
+ "nq": 36,
21
+ "nv": 35,
22
+ "nu": 29,
23
+ "nbody": 31,
24
+ "npair": 502,
25
+ "timestep": 0.005,
26
+ "substeps_per_control_step": 4,
27
+ "solver": "Newton",
28
+ "cone": "pyramidal",
29
+ "integrator": "implicitfast",
30
+ "robot": "mjlab",
31
+ "source": "MuJoCo Menagerie unitree_g1/scene_mjx.xml at f3b6013 (Unitree Robotics, BSD-3-Clause), modified after mjlab's G1 configuration: sole capsules, explicit contact pairs, contact and joint parameters, PD gains, ctrlrange, 5 ms timestep; meshes and textures removed. See README.md."
32
+ }
Binary file
@@ -0,0 +1,30 @@
1
+ """Optional parts of the package: load(package, feature, *names) imports a module (or several submodules of one package)
2
+ that a code path needs only for a given feature, and turns its absence into NotInRelease ("<feature> is not available
3
+ in this release of NablaEngine") instead of a bare ModuleNotFoundError. When the module is present, load is the same
4
+ import as `from package import name` (the same module objects, nothing else changes); an ImportError raised inside a
5
+ present module propagates unchanged."""
6
+ import importlib
7
+
8
+ __all__ = ["BAM", "FOREST", "NotInRelease", "load"]
9
+
10
+ FOREST = "the forest engine (models outside the G1 class: several trees under the world, or no free root)"
11
+ BAM = "the BAM servo model (actuator='bam')"
12
+
13
+
14
+ class NotInRelease(NotImplementedError):
15
+ """A feature whose modules this installation of NablaEngine does not include."""
16
+
17
+
18
+ def load(package, feature, *names):
19
+ """The module `package` (no names), the submodule package.<name> (one name) or a tuple of them (several names).
20
+ NotInRelease when one of them (or the package) is not installed."""
21
+ mods = [f"{package}.{n}" for n in names] if names else [package]
22
+ out = []
23
+ for mod in mods:
24
+ try:
25
+ out.append(importlib.import_module(mod))
26
+ except ModuleNotFoundError as e:
27
+ if e.name is None or not (mod == e.name or mod.startswith(e.name + ".")):
28
+ raise
29
+ raise NotInRelease(f"{feature} is not available in this release of NablaEngine") from None
30
+ return out[0] if len(out) == 1 else tuple(out)
nablaengine/_paths.py ADDED
@@ -0,0 +1,38 @@
1
+ """Where the default model and corpus are (standard library only: torch_ffi uses it without mujoco).
2
+
3
+ Lookup order of the fixtures directory (nablaengine.fixtures.fixtures_dir) and of the benchmark corpora's directory
4
+ (fixtures.bench_dir):
5
+ 1. $DK_FIXTURES / $DK_BENCH_DATA when set and not empty;
6
+ 2. the source checkout this package is imported from: <checkout>/fixtures/mjlab and <checkout>/benchmarks/data
7
+ (PYTHONPATH=<checkout>/src, a .pth file or pip install -e), when they exist;
8
+ 3. the copy packaged with the wheel: nablaengine/_fixtures/mjlab (the G1 model: g1_train.mjb, g1_meta.json, its
9
+ LICENSE and README.md) and nablaengine/_fixtures/data (the corpus mf_s0.npz), _fixtures/README.md.
10
+ When neither exists, the checkout paths are returned, so error messages name the expected location."""
11
+
12
+ from pathlib import Path
13
+
14
+ PACKAGE = Path(__file__).resolve().parent
15
+ CHECKOUT = PACKAGE.parents[1]
16
+ PACKAGED = PACKAGE / "_fixtures"
17
+ CHECKOUT_FIXTURES = CHECKOUT / "fixtures" / "mjlab"
18
+ CHECKOUT_BENCH = CHECKOUT / "benchmarks" / "data"
19
+ PACKAGED_FIXTURES = PACKAGED / "mjlab"
20
+ PACKAGED_BENCH = PACKAGED / "data"
21
+
22
+
23
+ def default_fixtures():
24
+ """The default fixtures directory: the checkout's fixtures/mjlab, else the packaged copy (where g1_meta.json
25
+ exists), else the checkout's path."""
26
+ for d in (CHECKOUT_FIXTURES, PACKAGED_FIXTURES):
27
+ if (d / "g1_meta.json").is_file():
28
+ return d
29
+ return CHECKOUT_FIXTURES
30
+
31
+
32
+ def default_bench():
33
+ """The default benchmark corpora's directory: the checkout's benchmarks/data, else the packaged copy (where the
34
+ directory exists), else the checkout's path."""
35
+ for d in (CHECKOUT_BENCH, PACKAGED_BENCH):
36
+ if d.is_dir():
37
+ return d
38
+ return CHECKOUT_BENCH
@@ -0,0 +1,169 @@
1
+ """Actuator models on top of the model's MJCF actuators (opt-in): init(actuator=...) of nablaengine.jax_ffi,
2
+ nablaengine.torch_ffi (init / build) and jax_ffi.EnginePhysics."""
3
+
4
+ from dataclasses import dataclass
5
+
6
+ from nablaengine.motor import PRESETS, MotorCurve, MotorLimits
7
+
8
+ __all__ = ["Actuators", "Bam", "Spec", "TorqueSpeed", "resolve"]
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class TorqueSpeed:
13
+ """Torque-speed limits of one motor type (nablaengine.motor.MotorCurve) on the joints its pattern matches."""
14
+ curve: MotorCurve
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Bam:
19
+ """Rhoban's BAM servo model (Better Actuator Models, model M6) with a parameter set ("xl330/m6", bundled, or a path
20
+ to a BAM parameters json of an XL330 M6 set), the servo firmware's proportional gain kp_fw, the nominal supply
21
+ voltage vin_nom (V), the supply's floor vin_min (V) and the firmware current limit max_current ("firmware": the
22
+ servo's own, 1.75 A for the XL330; a current in A; None: off). Both engines (e.g. a single-tree robot with a free root and
23
+ one position servo per hinge). nablaengine.actuators.bam has the model and its engine form."""
24
+ params: str = "xl330/m6"
25
+ kp_fw: float = 200.0
26
+ vin_nom: float = 7.4
27
+ vin_min: float = 6.0
28
+ max_current: object = "firmware"
29
+
30
+ def key(self):
31
+ mc = self.max_current if self.max_current in (None, "firmware") else f"{float(self.max_current):g}"
32
+ return (f"bam:{self.params}:kp_fw={float(self.kp_fw):g}:vin_nom={float(self.vin_nom):g}"
33
+ f":vin_min={float(self.vin_min):g}:max_current={mc}")
34
+
35
+
36
+ class Actuators:
37
+ """Actuator models by joint: Actuators((joint-name regular expression, model), ...), model a TorqueSpeed or a Bam
38
+ (a bare MotorCurve is taken as TorqueSpeed); each actuated joint takes the first pattern that matches its name in
39
+ full. name: the build key's label (as MotorLimits.name)."""
40
+
41
+ def __init__(self, *entries, name="custom"):
42
+ out = []
43
+ for e in entries:
44
+ if not (isinstance(e, tuple) and len(e) == 2 and isinstance(e[0], str)):
45
+ raise TypeError(f"Actuators: entries are (joint regex, model) pairs, not {e!r}")
46
+ p, mdl = e
47
+ if isinstance(mdl, MotorCurve):
48
+ mdl = TorqueSpeed(mdl)
49
+ if not isinstance(mdl, (TorqueSpeed, Bam)):
50
+ raise TypeError(f"Actuators: the model of {p!r} must be a TorqueSpeed, a Bam or a MotorCurve, not "
51
+ f"{type(mdl).__name__}")
52
+ out.append((p, mdl))
53
+ if not out:
54
+ raise ValueError("Actuators: no entries")
55
+ self.entries, self.name = tuple(out), str(name)
56
+
57
+ def __repr__(self):
58
+ return f"Actuators({', '.join(repr(e) for e in self.entries)}, name={self.name!r})"
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Spec:
63
+ """A resolved actuator option: motor (a MotorLimits: torque-speed limits, the existing motor hooks) or bam (a Bam
64
+ on every actuated joint), never both (yet)."""
65
+ motor: MotorLimits = None
66
+ bam: Bam = None
67
+
68
+ def key(self, m):
69
+ """The build's info["actuator"]: MotorLimits.key(m) for torque-speed limits (= info["motor_limits"])."""
70
+ return self.motor.key(m) if self.motor is not None else self.bam.key()
71
+
72
+
73
+ def _from_kind(d, where):
74
+ d = dict(d)
75
+ kind = d.pop("kind")
76
+ if kind == "bam":
77
+ try:
78
+ return Spec(bam=Bam(**d))
79
+ except TypeError as e:
80
+ raise TypeError(f"{where}={{'kind': 'bam', ...}}: {e} (keys: params, kp_fw, vin_nom, vin_min, max_current)") from None
81
+ if kind in ("torque_speed", "motor_limits"):
82
+ if set(d) - {"curves", "name", "require_all"}:
83
+ raise TypeError(f"{where}={{'kind': {kind!r}, ...}}: keys curves, name, require_all")
84
+ c = d.get("curves")
85
+ return Spec(motor=MotorLimits(curves=tuple(c.items()) if isinstance(c, dict) else tuple(c),
86
+ name=d.get("name", "custom"), require_all=d.get("require_all", True)))
87
+ raise ValueError(f"{where}: unknown kind {kind!r} (one of 'bam', 'torque_speed')")
88
+
89
+
90
+ def _from_actuators(a):
91
+ ts = [(p, x.curve) for p, x in a.entries if isinstance(x, TorqueSpeed)]
92
+ bam = [x for _, x in a.entries if isinstance(x, Bam)]
93
+ if not bam:
94
+ return Spec(motor=MotorLimits(curves=tuple(ts), name=a.name))
95
+ if ts:
96
+ raise ValueError("actuator: BAM together with torque-speed limits in one build is not supported")
97
+ if len(set(bam)) != 1 or a.entries[-1][0] != ".*":
98
+ raise ValueError("actuator: BAM takes one Bam model on every actuated joint (Actuators((r'.*', Bam(...)),))")
99
+ return Spec(bam=bam[0])
100
+
101
+
102
+ def resolve(actuator=None, motor_limits=None, where="actuator"):
103
+ """The Spec of init's actuator= / motor_limits= (aliases; both given raises ValueError), None for none. Accepts
104
+ None / False, a preset name ("unitree_g1", "mjlab_g1_dc") or "bam", a MotorLimits, a TorqueSpeed (every actuated
105
+ joint), a Bam (every actuated joint), a {joint regex: MotorCurve | TorqueSpeed | Bam} dict, a {"kind": "bam" |
106
+ "torque_speed", ...} dict, an Actuators or a Spec."""
107
+ a_off, m_off = actuator is None or actuator is False, motor_limits is None or motor_limits is False
108
+ if not a_off and not m_off:
109
+ raise ValueError(f"{where}: actuator= and motor_limits= are aliases; give one of them, not both")
110
+ x, name = (motor_limits, "motor_limits") if a_off else (actuator, "actuator")
111
+ if x is None or x is False:
112
+ return None
113
+ if isinstance(x, Spec):
114
+ return x
115
+ if isinstance(x, MotorLimits):
116
+ return Spec(motor=x)
117
+ if isinstance(x, str):
118
+ if x == "bam":
119
+ return Spec(bam=Bam())
120
+ if x not in PRESETS:
121
+ raise ValueError(f"{name}={x!r}: one of {sorted(PRESETS) + ['bam']}, a MotorLimits, an Actuators or a "
122
+ "dict")
123
+ return Spec(motor=PRESETS[x])
124
+ if isinstance(x, TorqueSpeed):
125
+ return Spec(motor=MotorLimits(curves=((r".*", x.curve),)))
126
+ if isinstance(x, Bam):
127
+ return Spec(bam=x)
128
+ if isinstance(x, Actuators):
129
+ return _from_actuators(x)
130
+ if isinstance(x, dict):
131
+ if "kind" in x:
132
+ return _from_kind(x, name)
133
+ if all(isinstance(v, MotorCurve) for v in x.values()):
134
+ return Spec(motor=MotorLimits(curves=tuple(x.items())))
135
+ return _from_actuators(Actuators(*x.items()))
136
+ raise TypeError(f"{name}: None, a preset name, 'bam', a MotorLimits, a TorqueSpeed, a Bam, an Actuators or a dict, "
137
+ f"not {type(x).__name__}")
138
+
139
+
140
+ def check_engine(spec, forest, where):
141
+ """Refuse what the model's engine does not simulate (both engines have the BAM servo model: g1_engine /
142
+ forest_engine.bam_hooks; nothing is refused today)."""
143
+ return
144
+
145
+
146
+ def check_bam_build(spec, where, terrain=None, params=None, contact_forces=False):
147
+ """Refuse the build options BAM does not support yet (ValueError): a terrain build, per-world parameters, the
148
+ contact-force table, DK_CLAMP_IMPLICIT=2."""
149
+ if spec is None or spec.bam is None:
150
+ return
151
+ bad = [what for on, what in ((terrain is not None, "a terrain build"), (bool(params), "per-world parameters "
152
+ "(params=)"), (bool(contact_forces), "contact_forces=True")) if on]
153
+ from nablaengine.g1_engine import step
154
+ if step.clamp_implicit()[0] == 2:
155
+ bad.append("DK_CLAMP_IMPLICIT=2")
156
+ if bad:
157
+ raise ValueError(f"{where}: actuator='bam' is not available with {', '.join(bad)} yet")
158
+
159
+
160
+ def prepare_model(spec, m):
161
+ """The model the build simulates: bam.prepare(m, spec.bam) for BAM (the servo model's engine form, checked), else
162
+ m itself."""
163
+ if spec is None or spec.bam is None:
164
+ return m
165
+ from nablaengine._optional import BAM, load
166
+ bam = load("nablaengine.actuators", BAM, "bam")
167
+ out = bam.prepare(m, spec.bam)
168
+ bam.check_model(out, spec.bam)
169
+ return out