Robots and state¶
The Unitree G1's specification and the state layout shared by simulators, world models, tasks and motion libraries.
ndm_gym.robots.g1
¶
Unitree G1 (29 DoF), following BeyondMimic's actuator model.
The URDF is the one the LAFAN1 motions were retargeted to (g1_29dof_rev_1_0). Joint drives are
implicit PD with a 10 Hz natural frequency and damping ratio 2 on the reflected motor armature, and
the action scale is 0.25 * effort_limit / stiffness, as in BeyondMimic. The Isaac Lab asset built from
this spec lives in ndm_gym.sim.rigid.isaaclab_mjwarp.
ndm_gym.state
¶
State layout, sim context and control rate shared by simulators, world models, tasks and motion libraries.
State tuple S = (p, R, v, w, q, qd): pelvis position, rotation matrix, world linear/angular
velocity of the pelvis link frame, joint positions and velocities. Sim context
xi = [friction, joint calibration offsets (NUM_J), torso center-of-mass offset (3)].
ndm_gym.robots.hands
¶
Dexterous hands on a position-controlled floating palm, as in SPIDER's hand-object scenes: the XHand (12 finger joints), the Allegro hand (16, four fingers) and the Inspire hand (12).
A hand is read from its compiled scene. Its joints are the actuated ones in the order of the scene's actuators: the
palm's three slides and three hinges, then the fingers' hinges. Its state is their positions and velocities.
HandKinematics is the differentiable forward kinematics of the tracked keypoints (the palm and the fingertips the
hand has), shared by the reference, the simulator's states and the world model's predictions.
HandKinematics
¶
HandKinematics(model: MjModel, device: str)
Keypoint positions and the palm's rotation from the joint positions, for a compiled scene model.
forward
¶
forward(q: Tensor) -> tuple[torch.Tensor, torch.Tensor]
Joint positions (..., num_joints) -> keypoint positions (..., num_keypoints, 3) and the palm's rotation (..., 3, 3).
palm
¶
palm(q: Tensor) -> tuple[torch.Tensor, torch.Tensor]
forward's palm alone: its keypoint (..., 1, 3) and rotation (..., 3, 3), from the bodies of the palm's chain
(the same operations, so the same values); what the world model reads (train_hand --wm_palm_fk).
hand_joints
¶
hand_joints(model: MjModel) -> list[int]
The ids of the hand's joints in the order of the scene's actuators: the palm's slides and hinges, the fingers'.
hand_keypoints
¶
hand_keypoints(model: MjModel) -> list[int]
The ids of the tracked sites: the palm, then the fingertips the hand has (thumb to pinky).
scene_indices
¶
scene_indices(
model: MjModel,
) -> dict[str, np.ndarray | int]
Where the hand's joints, their actuators and the object's free joint sit in the scene's qpos, qvel and ctrl.
ndm_gym.robots.objects
¶
Interacted objects of the human-object-interaction tasks: shape, nominal physical properties used in evaluation, and the ranges training draws from.
largebox: OMOMO's large box (OmniRetarget/Holosoma largebox.obj, 0.471 x 0.459 x 0.408 m, centered on its
origin within 6 mm), modeled as a cuboid; training ranges follow Holosoma's randomization of that box (mass 1-4 kg,
sliding friction 0.1-0.6), evaluation uses their midpoints.
ndm_gym.robots.muscles
¶
MuscleVAE's muscle model (Feng, Xu and Liu, SIGGRAPH Asia 2023) for a batch of environments, in torch.
From the body poses: the anchor positions (blended between two bodies near a joint), the polyline muscle lengths and their rates, the Hill-type curves (rigid tendon, no pennation), the muscle-space PD force clipped to the range the 3CC-r fatigue model allows, the activation by inverting the Hill model, the 3CC-r fatigue update, and the anchor forces summed into one wrench per body. Re-implemented from the paper (Sec. 3, App. A) and the equations of the released code, wangchek/MuscleVAE_ @ 54c001c, which has no license: nothing is copied from it. References are to that code: BE = ModifyODESrc/VclSimuBackend.pyx, CHR = Muscle/muscle_character.py, ENV = MuscleVAECore/Env/muscle_env.py.
Conventions: positions in the world frame, orientations as rotation matrices (v_world = R v_body), each body's origin at its center of mass (the origin of an ODE body, as in their simulator; the converted character keeps it). Per-muscle tensors are (..., M), per-anchor (..., A, 3), per-body (..., N, 3), for any leading batch shape. Everything at step time is a fixed sequence of elementwise ops and gathers with precomputed indices: no Python loop over muscles or anchors, no host synchronization, no matmul (so TF32 matmul settings cannot round it), and the same result on every run for the same inputs. That holds for the muscle model only: the GPU physics it drives (MuJoCo-Warp, ndm_gym.sim.rigid.muscle_sim) is not run-to-run deterministic.
Parameter sets (MUSCLE_MODELS), both on the converted table's kp = f0 x manual_muscle_kp4.txt (ENV:101) and f0max = 1.5 x MuscleVAE_force.txt (ENV:103), with r = 2 and L_D = L_R = 50 (ENV:111-115) at 120 Hz:
released(the default) is the released code's behavior, so that its pretrained models run in this port: kd = 2 sqrt(kp) (CHR:128-129); fatigue rates F = 0.1, R = 0.02 (0.05 and 0.01 times config.yml's fatigue_adjust_ratio 2, ENV:111-113); length rates divided by fps instead of multiplied, (l - l_prev) / 120 (BE:4725- 4726), which keeps the force-velocity factor within about 1e-3 of 1 and makes the damping term 14,400 times smaller than kd (l - l_prev) / dt; and zero velocity in the Hill inversion, because CHR:221 overwrites the previous length before CHR:237 reads it.paper: kd = 0.1 kp, F = 0.01, R = 0.002 (App. C.1); length rates (l - l_prev) / dt (Eq. 24), also in the Hill inversion (Eq. 5).
One substep (ENV:373-381, :meth:MuscleModel.substep): lengths from the body poses, the PD force within the bounds of
the current fatigue state, applied at the anchors; the activation that produces it; the fatigue update with that
activation; then the physics step (the caller's). Resets draw the fatigue state as MuscleVAE does
(:meth:MuscleModel.random_fatigue).
MuscleTable
dataclass
¶
MuscleTable(
names: tuple[str, ...],
num_bodies: int,
anchor_count: ndarray,
anchor_body0: ndarray,
anchor_local0: ndarray,
anchor_body1: ndarray,
anchor_local1: ndarray,
anchor_weight0: ndarray,
rest_length: ndarray,
lm: ndarray,
lt: ndarray,
f0: ndarray,
f0max: ndarray,
kp: ndarray,
part: ndarray,
)
Static muscle data (numpy). The anchors of a muscle are contiguous and in path order, from origin to insertion.
MuscleParams
dataclass
¶
MuscleParams(
kd: str = "2*sqrt(kp)",
fatigue_F: float = 0.1,
fatigue_R: float = 0.02,
fatigue_r: float = 2.0,
LD: float = 50.0,
LR: float = 50.0,
sim_hz: float = 120.0,
rate: str = "delta/fps",
inversion_rate: str = "zero",
gamma: float = 0.5,
k_pe: float = 4.0,
e_mo: float = 0.6,
fpe_cap: float = 2.0,
)
The muscle model's rules and constants; the defaults are the released code's (MUSCLE_MODELS["released"]).
MuscleStep
¶
Bases: NamedTuple
Everything one substep computes (:meth:MuscleModel.substep); fatigue values are the next substep's.
MuscleModel
¶
MuscleModel(
table: MuscleTable,
params: MuscleParams | None = None,
device: str | device = "cpu",
dtype=torch.float32,
)
The muscle model of one character on one device, for any batch of environments.
The index tensors built here (anchor points, polyline segments, per-body chunks of anchors) turn every step into a fixed sequence of row gathers and elementwise ops. Per-anchor, per-segment and per-body tensors are kept entity-major internally, (K, B, ...) for the B environments of the flattened batch, so that each gather copies whole rows; inputs and outputs are batch-major, (..., K, ...), the per-anchor outputs as views of the internal layout.
anchor_positions
¶
anchor_positions(
body_pos: Tensor, body_rot: Tensor
) -> torch.Tensor
World anchor positions (..., A, 3) from body origins (..., N, 3) and rotations (..., N, 3, 3): a blended anchor is w0 (R_0 x_0 + p_0) + (1 - w0) (R_1 x_1 + p_1) (Eq. 18, BE:2905-2970), any other R_0 x_0 + p_0.
lengths
¶
lengths(anchor_pos: Tensor) -> torch.Tensor
Muscle lengths (..., M): the polyline through the anchors (Eq. 19, BE:3019-3031).
anchor_forces
¶
anchor_forces(
anchor_pos: Tensor, force: Tensor
) -> torch.Tensor
Force vectors at the anchors (..., A, 3) for muscle forces (..., M): f times the unit vector to the next anchor plus the unit vector to the previous one, one of them at the path's ends (Eq. 20, BE:3597-3663).
body_wrench
¶
body_wrench(
anchor_pos: Tensor,
anchor_force: Tensor,
body_pos: Tensor,
) -> tuple[torch.Tensor, torch.Tensor]
Per body (..., N, 3): the sum of the forces at its anchors and of their moments about its origin. Each anchor pushes only its body0, the nearer body of a blended anchor, at the anchor's blended position (CHR:218-220, BE:2882-2899, dBodyAddForceAtPos).
anchor_velocities
¶
anchor_velocities(
body_pos: Tensor,
body_rot: Tensor,
body_vel: Tensor,
body_angvel: Tensor,
) -> torch.Tensor
World anchor velocities (..., A, 3) from the bodies' poses, origin velocities and angular velocities (..., N, 3):
the time derivative of :meth:anchor_positions, sum of w (v + omega x R x) over an anchor's points, which is
that map with R replaced by its derivative [omega]x R and p by v.
length_rates
¶
length_rates(
anchor_pos: Tensor, anchor_vel: Tensor
) -> torch.Tensor
Time derivatives of the muscle lengths (..., M) from the anchors' positions and velocities (..., A, 3): over each segment, its ends' relative velocity along it.
path_points
¶
path_points(
anchor_pos: Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
Per muscle (..., M, 3): the point halfway along its polyline (by arc length), and the unit directions of its first and last segments (from the origin towards the insertion).
muscle_bodies
¶
muscle_bodies() -> list[set[int]]
The bodies each muscle's anchors move with (both bodies of a blended anchor).
normalized_length
¶
normalized_length(length: Tensor) -> torch.Tensor
(l / l_Tpose - lt) / lm (Eq. 23, BE:4707-4714); also their scaled muscle length (BE:3225-3245).
target_length
¶
target_length(action: Tensor) -> torch.Tensor
PD target lengths (1 + a) l_Tpose of actions (..., M) (Eq. 11, ENV:431-433).
rates
¶
rates(
length: Tensor, length_prev: Tensor
) -> tuple[torch.Tensor, torch.Tensor]
Length rate (the PD's) and normalized length rate (the force-velocity factor's) from the previous substep's
lengths: the change times sim_hz, or divided by it with rate="delta/fps" (the released code, BE:4725-4726).
part_fatigue
¶
part_fatigue(
MA: Tensor, MR: Tensor, MF: Tensor
) -> torch.Tensor
The fatigue state (..., 15): f0-weighted means of MA, MR and MF over each body part, in that order (B.4, CHR:333-337, motion_utils.character_muscle_state).
random_fatigue
¶
random_fatigue(
batch: tuple[int, ...],
generator: Generator | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
MuscleVAE's random initial fatigue state (ENV:302-305; mode 0 of CHR:339-356, BE:4448-4502): for each body
part a time uniform in [0, 10) s and the state of :func:fatigue_init_curve at step int(t / (1 / sim_hz)); every
muscle takes its part's state. Returns (MA, MR, MF), each (*batch, M).
substep
¶
substep(
body_pos,
body_rot,
length_prev,
length_target,
MA,
MR,
MF,
) -> MuscleStep
One muscle substep from the body poses (..., N, 3) and (..., N, 3, 3), the previous substep's lengths, the PD targets and the fatigue state (..., M) (ENV:373-381): the anchor forces and wrenches to apply before the physics step, and the next fatigue state.
damping_gain
¶
damping_gain(kp, p: MuscleParams)
The PD damping kd of stiffnesses kp (numpy or torch) by the parameter set's rule.
hill_curves
¶
hill_curves(
l_norm: Tensor, v_norm: Tensor, p: MuscleParams
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
Active force-length, force-velocity and passive force-length factors of the normalized length and its rate (Eq. 25, BE:4715-4731). Each force-velocity branch is evaluated on its own side of 0, so neither divides by zero.
activation_bounds
¶
activation_bounds(
MA: Tensor, MR: Tensor, p: MuscleParams
) -> tuple[torch.Tensor, torch.Tensor]
The next activation's range under the 3CC-r model, target load 0 and 1 (Eq. 34-35, BE:4734-4743).
pd_force
¶
pd_force(
length,
l_target,
l_rate,
kp,
kd,
f0max,
fl,
fv,
fpe,
lo,
hi,
)
Muscle-space PD force, clipped to [0, inf) and then to the Hill force at activations [lo, hi] (Eq. 4, 6, 9, 10, BE:4732-4758). Returns the force, the PD force before any clipping, and the lower and upper bounds. The bounds are tested upper first, as the released code does (they cross only where the force-velocity factor is negative).
invert_hill
¶
invert_hill(
f, f0max, fl, fv, fpe, lo, hi
) -> tuple[torch.Tensor, torch.Tensor]
The activation whose Hill force is f (Eq. 5, BE:4834-4880): the active part of f over its maximum, clipped to [lo, hi] (upper bound first). Returns it and the value before the [lo, hi] clip.
hill_force
¶
hill_force(a, f0max, fl, fv, fpe) -> torch.Tensor
The Hill-type force of activation a (Eq. 22).
fatigue_step
¶
fatigue_step(
MA, MR, MF, a, p: MuscleParams
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
One forward-Euler step of the 3CC-r model (Eq. 26-28) with the next activation a given (App. A.3.1, BE:3738-3792):
the transfer C(u) that leads from MA to a, with the target load u recovered from a and clipped to [0, 1]; the rest
recovery multiplier r applies while relaxing. Returns the next (MA, MR, MF) = (a, ...). With a in the bounds of
:func:activation_bounds and MA + MR <= 1, MA + MR + MF is conserved.
fatigue_init_curve
¶
fatigue_init_curve(p: MuscleParams) -> np.ndarray
The curve MuscleVAE draws initial fatigue states from (CHR:280-292, BE:4399-4441): one muscle from (MA, MR, MF) = (0, 1, 0) under the target load 0.5 for 20 s, then 0 until 40 s, by forward-Euler steps of the 3CC-r model at sim_hz with the target-load controller (BE:3694-3731): relaxing towards the load when MA >= load (rest recovery r R), else developing towards it from the resting pool, at most at the rate LD MR. Row k is the state before step k; (steps, 3) float64, with their step counts int(sim_hz / (1 / t)).
ndm_gym.robots.musclevae_char
¶
MuscleVAE's muscle-actuated character (Feng, Xu and Liu, SIGGRAPH Asia 2023; wangchek/MuscleVAE_ @ 54c001c): 23 rigid bodies, 22 joints (14 ball, 8 hinge), 61.4 kg, driven by 284 muscles through 1,212 anchors, simulated at 120 Hz and controlled at 20 Hz.
MuscleVAE's repository has no license, so its files are never redistributed: tools/download_musclevae.sh fetches it at
the pinned commit into data/musclevae/src, and tools/convert_musclevae.py writes the assets this module loads into
data/musclevae/: character.xml (MJCF), character.json (bodies, joints and the conventions), muscles.json (the muscle
table) and clips/ (their walk, run and jump references at 20 Hz). The converter's docstring records every convention:
Z-up with the character facing +x, body origins at the bodies' centers of mass (their simulator's), body frames
aligned with the world in the T-pose; muscle forces are computed by :mod:ndm_gym.robots.muscles. The character's forward
kinematics and the per-axis Euler angles of its ball joints, which their simulator limits and MuJoCo cannot, are here too.
load_character
¶
load_character(path: str = CHARACTER_PATH) -> dict
The converted character description (character.json), checked against this module's constants.
load_muscle_table
¶
load_muscle_table(path: str = MUSCLES_PATH) -> MuscleTable
The converted muscle table (muscles.json) as a :class:~ndm_gym.robots.muscles.MuscleTable.
muscle_model
¶
muscle_model(
model: str = "released",
device: str | device = "cpu",
dtype: dtype = torch.float32,
) -> MuscleModel
The character's muscle model with the released (default) or paper parameters (ndm_gym.robots.muscles).
forward_kinematics
¶
forward_kinematics(
root_pos: Tensor,
root_quat: Tensor,
joint_qpos: Tensor,
char: dict | None = None,
)
Body positions (..., 23, 3) (their centers of mass) and rotations (..., 23, 3, 3) of the character's joint
positions in the clips' layout: root_pos (..., 3), root_quat (..., 4) wxyz and joint_qpos (..., 64), as
MuJoCo's forward kinematics of character.xml. Body frames are aligned with the world in the T-pose, so a body b
below joint j with T-pose anchor a_j has R_b = R_p L_j and p_b = p_p + R_p (a_j - c_p) + R_b (c_b - a_j), with L_j
the ball joint's rotation or the hinge's rotation about its axis and c the T-pose centers of mass.
ball_euler_angles
¶
ball_euler_angles(local: Tensor) -> torch.Tensor
The three angles their simulator limits on a ball joint (an ODE AMotor in Euler mode, BE:17727-17750 and ODE's
amotor.cpp), of child rotations local (..., 3, 3) relative to the parent (our frame): axis 0, their x (our y),
fixed in the child; axis 2, their z (our x), fixed in the parent; axis 1 their cross product; the reference vectors
of the T-pose. Returns (..., 3), the angles about their x, y, z (character.json's euler_limits order), which satisfy
local = Rot(z, a2) Rot(y, a1) Rot(x, a0) in their axes.
ball_euler_limits
¶
ball_euler_limits(
char: dict | None = None,
) -> tuple[np.ndarray, np.ndarray]
Their per-axis Euler limits (rad, about their x, y, z) of the ball joints in BALL_JOINTS order: lo, hi (14, 3).
ndm_gym.robots.quadrotor
¶
A racing quadrotor as one rigid body: the open-design 5-inch drone of Race Against the Machine (Bosello et al., RA-L 2024).
No MJCF of the drone is published; mjcf writes one from the paper's specification: 870 g with the battery, 215 mm between
diagonal propellers, a thrust-to-weight ratio of 7.5 measured on a load cell. Not in the paper, and estimates here
(QuadrotorSpec): the inertia (2.9, 2.4 and 5.0 g m^2, of the size of a 5-inch racing quadrotor's of this mass: four
motors with their propellers, 45 g each, on the arms and the rest as a box of 14 x 6 x 7 cm give 1.5, 2.4 and 3.4 g m^2),
a linear drag and the rate controller's gains. evaluate_quadrotor --inertia_scale (and --drag_scale,
--mass_scale) flies a policy on a model with other values.
The drone is commanded as its flight controller is, by a collective thrust and body rates (CTBR): the thrust is a force along the body's z axis; each body rate is tracked by a proportional controller's torque about its axis, limited to what the propellers' differential thrust gives. Both are MuJoCo actuators on a site (a motor and three velocity servos), so the rate loop runs at the physics rate inside the simulator. There is no contact: the flights stay in the air. The integrator is MuJoCo's Euler, which MuJoCo and MuJoCo-Warp step alike here (the drag implicitly, the servos explicitly; with implicitfast the two treat a site's velocity servo differently and the body rates of one control step differ by several per cent).
mjcf
¶
mjcf(spec: QuadrotorSpec = QuadrotorSpec()) -> str
The drone's MJCF: a free body, the thrust and the three rate servos on its site, no contacts.
load_model
¶
load_model(spec: QuadrotorSpec = QuadrotorSpec())
The drone's mujoco.MjModel, with the linear drag as damping of the free joint's translation (the compiler sets
one damping for a joint's six degrees of freedom; the rotation's stays zero).
ndm_gym.robots.go2
¶
Unitree Go2 (MuJoCo Menagerie's unitree_go2) with joint position servos, for quadruped motion tracking.
The trunk is a free body and each leg a chain of three hinges (hip abduction, thigh, calf), so the robot's state is
MuJoCo's: qpos (19: the trunk's position and quaternion w, x, y, z, then the 12 joints in JOINT_NAMES' order) and
qvel (18: the trunk's world linear velocity and body-frame angular velocity, then the joints'). Menagerie's motors
take torques; load_scene turns them into position servos about the policy's targets (gains KP, KD) with the
motors' torque limits, sets the joints' damping to JOINT_DAMPING (Unitree's own model's, in place of Menagerie's 2),
and zeroes the geoms' margins, which MuJoCo-Warp refuses with multi-CCD. Go2Kinematics is the
differentiable forward kinematics of the tracked keypoints (the trunk and the four feet), built from the compiled model,
shared by the reference, the simulator's states and the world model's predictions.
Go2Kinematics
¶
Go2Kinematics(model: MjModel, device: str)
Keypoint positions and the trunk's rotation from qpos, for a compiled model model.
forward
¶
forward(qpos: Tensor) -> tuple[torch.Tensor, torch.Tensor]
qpos (..., NQ) -> keypoint positions (..., NUM_KP, 3), the trunk's first, and the trunk's rotation (..., 3, 3).
load_scene
¶
load_scene(
path: str = SCENE_PATH,
kp: float = KP,
kd: float = KD,
timestep: float = SIM_DT,
joint_damping: float | None = JOINT_DAMPING,
) -> mujoco.MjModel
Menagerie's Go2 scene (the robot and the floor) with each motor turned into a position servo of gains kp and
kd: its control a joint position within the joint's range, its force limited to the motor's torque range. The
geoms' margins are zeroed (MuJoCo-Warp does not take a non-zero margin with multi-CCD).