unisim.backend.genesis.backend.GenesisBackend¶
- class unisim.backend.genesis.backend.GenesisBackend[source]¶
Bases:
SimBackendIndependent Genesis backend exposed through the host NumPy profile.
Construction performs dependency loading, the MJCF cold-path scan, the process-wide
gs.init(once), and scene/entity/sensor creation;materialize()builds the batched solver state and binds all runtime caches. Terrain, geom-name contracts, and site Jacobians fail closed. Native interactive/offscreen rendering attaches lazily post-build (see the play contract section). Callclose()to end the process-wide Genesis session; re-initialization afterwards fails closed by design.- Parameters:
Methods
__init__(scene, num_envs, sim_dt, *[, ...])apply_body_force(body_ids, force[, torque])Apply a world-frame wrench at each body COM for the upcoming step.
Apply a scheduled interval randomization plan.
bind_height_scanner(*, hfield_geom_id, ...)Create a reusable height-field scanner on the init/cold path.
bind_host_bridge_io(spec)Compile a persistent transfer plan for a declared host bridge.
bind_mocap_pose(body_name)Resolve a mocap body once; unavailable capabilities fail at binding.
bind_packed_reset(*[, device])Begin a device-resident packed reset transaction.
bind_renderer([spacing, offset_mode, ...])Lazily attach the Genesis viewer and/or an offscreen camera.
bind_sensor_data(names)Materialize a validated view over named tensor sensors.
Capture one offscreen RGB frame (self-initializes headless+capture).
Release cold-path scene artifacts owned by the backend.
close()End the process-wide Genesis session; re-init afterwards fails closed.
MJCF
ctrlrangemetadata; Genesis does not enforce it in-engine.Return per-joint (kp, kd) arrays from the backend model.
Return each actuator's target single-DoF joint in control-vector order.
Return actuator names in control-vector order on the cold path.
get_body_id(name)Resolve one body/link name through the backend contract.
get_body_ids(names)Resolve body/link names to backend integer IDs.
get_body_ipos([env_ids])Return body center-of-mass offsets in each body's local frame, in meters.
Return the backend body-mass table.
get_body_subtree_ids(root_body_id)Return body ids in the subtree rooted at
root_body_id.get_capabilities(*[, profile])Query semantic declarations plus authoritative DR/play/variant support.
Return default joint positions in canonical non-root qpos order.
Return default geometry sizes, shape (ngeom, 3).
Return the backend/model default qpos through a stable contract.
Return the backend dof-armature table.
Return cold-captured native Genesis DOF damping in public order.
Return cold-captured native Genesis friction loss in public order.
Declare only the per-env round-trip-measured DR items (REPORT §5.7).
get_entity_default_state(entity[, env_ids])Detached construction/keyframe defaults in selected environment order.
Return materialized physical entity names in the frozen public order.
get_entity_state(entity)Return detached root_pose/root_velocity/joint_positions/joint_velocities.
Return the owning body id for each geom.
Genesis-native recoded contype/conaffinity of collision geoms.
Return audited native Genesis geom-friction coefficients.
get_geom_id(name)Resolve one geom name through the backend contract.
Return backend geom names in backend id order.
get_geom_size(name)Return one geom size vector in backend geom-name order.
Return audited native Genesis contact impedance parameters.
Return audited native Genesis contact reference parameters.
Return the backend gravity vector.
Return a detached construction/materialization configuration snapshot.
Return a zero-initialized qvel vector compatible with
set_state_tensor.get_joint_dof_indices(names)Resolve joint names to absolute DoF indices in velocity space.
get_joint_dof_pos_indices(names)Resolve joint names to DoF indices in position space (qpos).
get_joint_dof_vel_indices(names)Resolve joint names to joint-section DoF indices in velocity space.
get_joint_range(*[, names])Return joint position limits, excluding the floating base.
get_joint_state_qpos_indices(names)Resolve single-DoF joints to full
set_state_tensorqpos columns.get_joint_state_qvel_indices(names)Resolve single-DoF joints to full
set_state_tensorqvel columns.get_keyframe_qpos(name)Return the full qpos for a named keyframe, including the floating base.
get_motion_body_ids(names)Resolve body IDs used by motion datasets.
Assemble contract
[time, qpos, qvel]rows in MJCF order.Return the
[time, qpos, qvel]snapshot layout (no mocap tail yet).Return backend-native play/render capabilities.
get_playback_mocap_state([env_index])Return copied
(mocap_pos, mocap_quat)arrays for detached playback.get_playback_model([env_index])Return the MJCF file path used by detached MuJoCo playback.
Return canonical qpos/qvel widths for packed tensor reset layout.
get_reset_term_default(term)Return canonical or variant-assigned Genesis reset defaults.
get_root_state_layout(root_body_name)Resolve one body's floating-root columns on the cold path.
Return the immutable materialized public addresses, never native handles.
Return the materialized scene path for diagnostics, when available.
Return the scene visual model file on the cold path, when available.
Return the complete public named-sensor inventory and widths.
Return the complete public named-sensor namespace.
get_sensor_view(name[, device])Return one stable supported device-resident sensor view.
get_site_ids(names)Resolve site names to integer ID arrays.
get_site_jacobian_w(site_id, dof_indices)Compute world-frame Jacobians for one site and selected DoF columns.
get_state_views([fields, device])Return stable qpos/qvel mirrors on Genesis' exact CUDA device.
Return fail-closed tensor methods and negotiable state fields.
Declare the optional tensor lifecycle without discovering SDKs.
Return runtime-selected diagnostics for optional tensor optimizations.
Return backend-materialized terrain metadata on the cold path.
get_tracked_body_views([body_names, device])Return all tracked-body fields in one public backend read.
Build the batched scene, cross-check the import, and bind caches.
render()Draw one interactive viewer frame (self-initializes interactive).
reset_entities(request)Validate the complete selected-entity request, then commit it once.
resolve_play_render_plan(*, ...)Resolve high-level playback mode into backend-owned render parameters.
run_playback(*, env, initialize, step, num_steps)Execute backend-owned playback for an env wrapper.
set_mocap_pose_tensor(body_name, ...)Write selected mocap poses through the declared tensor lifecycle.
set_physics_state(state)Restore a
get_physics_statesnapshot through the set_state path.Register an env-owned policy-control to physics-control converter.
set_state_tensor(env_indices, qpos, qvel[, ...])Commit selected CUDA state while preserving untouched rows.
set_state_tensor_mask(reset_mask, qpos, qvel)Commit full-width CUDA state selected by a persistent bool mask.
step_tensor(ctrl[, nsteps])Step the single-articulation CUDA profile without a host tensor detour.
Attributes
Coarse capability labels for clients that need a cheap feature check.
Return the backend-owned Genesis rigid entity.
Number of actuators.
Number of joint velocity DoFs, excluding the floating base.
Number of vectorized environments.
- __init__(scene, num_envs, sim_dt, *, base_name=None, push_body_name=None, device_id=None, integrator=None, constraint_solver=None, friction_cone=None, solver_iterations=None, **unexpected_kwargs)[source]¶
- materialize()[source]¶
Build the batched scene, cross-check the import, and bind caches.
Idempotent, and called lazily by the first state access: env constructors that validate state shapes before the explicit lifecycle point (ManagerBasedRlEnv builds its EntityScene before calling
materialize(), #1382) work like they do on the MuJoCo backend — the same pattern as the isaacgym backend’s lazy materialize. A closed backend cannot be materialized again.- Return type:
- get_tensor_execution()[source]¶
Declare the optional tensor lifecycle without discovering SDKs.
- Return type:
TensorExecution
- get_tensor_capabilities()[source]¶
Return fail-closed tensor methods and negotiable state fields.
- Return type:
TensorLifecycleCapabilities
- get_public_state_widths()[source]¶
Return canonical qpos/qvel widths for packed tensor reset layout.
- Return type:
PublicStateWidths
- get_state_views(fields=None, device=None)[source]¶
Return stable qpos/qvel mirrors on Genesis’ exact CUDA device.
- get_sensor_view(name, device=None)[source]¶
Return one stable supported device-resident sensor view.
- step_tensor(ctrl, nsteps=1)[source]¶
Step the single-articulation CUDA profile without a host tensor detour.
- set_state_tensor(env_indices, qpos, qvel, randomization=None)[source]¶
Commit selected CUDA state while preserving untouched rows.
- set_state_tensor_mask(reset_mask, qpos, qvel, randomization=None, *, full_refresh=False)[source]¶
Commit full-width CUDA state selected by a persistent bool mask.
Genesis’ public state setters consume a boolean environment mask directly, so the fixed-width reset boundary does not compact selected rows on the host or device.
- get_actuator_ctrl_range()[source]¶
MJCF
ctrlrangemetadata; Genesis does not enforce it in-engine.- Return type:
- get_actuator_joint_names()[source]¶
Return each actuator’s target single-DoF joint in control-vector order.
Backends must fail closed when an actuator does not target exactly one hinge/slide joint. Manager action terms use this cold-path metadata to map community joint selectors onto the backend control vector without inspecting backend-private model objects.
- get_keyframe_qpos(name)[source]¶
Return the full qpos for a named keyframe, including the floating base.
- get_default_qpos()[source]¶
Return the backend/model default qpos through a stable contract.
- Return type:
- get_default_dof_pos()[source]¶
Return default joint positions in canonical non-root qpos order.
The returned array is detached, one-dimensional, and excludes floating root coordinates. Backends whose DoF view is actuator-indexed must use that same actuator-target order here.
- Return type:
- get_init_qvel()[source]¶
Return a zero-initialized qvel vector compatible with
set_state_tensor.- Return type:
- Returns:
Zero-filled qvel array.
- get_root_state_layout(root_body_name)[source]¶
Resolve one body’s floating-root columns on the cold path.
Backends must verify that
root_body_nameowns a free/floating joint; fixed bodies and runtimes without body-to-root metadata fail closed. Name/model lookup is forbidden on reset and step hot paths, so callers cache either the returned layout or the unsupported result during scene materialization.- Parameters:
root_body_name (
str)- Return type:
RootStateLayout
- get_body_ids(names)[source]¶
Resolve body/link names to backend integer IDs.
- Parameters:
- Return type:
- Returns:
int32array with shape(len(names),).- Raises:
ValueError – If any name is not found.
- get_motion_body_ids(names)[source]¶
Resolve body IDs used by motion datasets.
Motion datasets are generated from MuJoCo, so the returned ids follow the MJCF body order with
worldbodyas id 0, regardless of the backend-native indexing used byget_body_ids.
- get_geom_size(name)[source]¶
Return one geom size vector in backend geom-name order.
get_default_geom_sizesreturns the complete table of default sizes, while this selector resolves one geom by name.
- get_geom_contact_masks()[source]¶
Genesis-native recoded contype/conaffinity of collision geoms.
Genesis re-synthesizes contype/conaffinity at import: the collision matrix semantics are preserved, but the integer values must NOT be compared against MuJoCo tables (REPORT #1372 §5.10).
- get_geom_friction()[source]¶
Return audited native Genesis geom-friction coefficients.
Columns follow Genesis’ public coefficient properties as
[sliding, torsional, rolling]. The values are captured from exact collision instances during construction; reset mutation and solver feature enablement are separate unsupported semantics.- Return type:
- get_body_ipos(env_ids=None)[source]¶
Return body center-of-mass offsets in each body’s local frame, in meters.
body_ipos[b]is the position of bodyb’s center of mass in that body’s own local coordinate frame; it is neither an inertia tensor nor a whole-subtree COM.Without
env_idsthe canonical model default table is returned with shape(nbody, 3)in backend body-id order. It never changes with reset randomization; fixed-variant backends expose their per-environment default baselines throughget_reset_term_default()instead.With
env_idsthe current effective per-environment values are returned with shape(len(env_ids), nbody, 3), inenv_idsorder. The values reflect every reset randomization applied so far, including composition withbase_com_offset; an environment untouched by a partial reset keeps its previous values. Backends that do not track per-environment inertial offsets fail closed withNotImplementedErrorfor this form.
- get_dof_damping()[source]¶
Return cold-captured native Genesis DOF damping in public order.
- Return type:
- get_dof_frictionloss()[source]¶
Return cold-captured native Genesis friction loss in public order.
- Return type:
- get_joint_range(*, names=None)[source]¶
Return joint position limits, excluding the floating base.
- Parameters:
names (
Sequence[str] |None) – Optional joint names in requested return order. Adapters that support named scalar joints resolve the model mapping internally.- Return type:
- Returns:
Array with shape
(num_dof, 2)and columns[low, high], orNonewhen the backend does not expose limits.When
namesis provided by a supporting adapter, the result has shape(len(names), 2). Hinge limits are radians, slide limits are meters, and joints without enabled limits return infinities.
- get_joint_dof_indices(names)[source]¶
Resolve joint names to absolute DoF indices in velocity space.
- get_joint_dof_pos_indices(names)[source]¶
Resolve joint names to DoF indices in position space (qpos).
Only single-DoF joints are supported; free joints are excluded.
- get_joint_dof_vel_indices(names)[source]¶
Resolve joint names to joint-section DoF indices in velocity space.
Unlike
get_joint_dof_indices(), the returned indices exclude any root/free-joint velocity columns. They address the same joint section used byget_joint_dof_pos_indices().
- get_joint_state_qpos_indices(names)[source]¶
Resolve single-DoF joints to full
set_state_tensorqpos columns.Unlike
get_joint_dof_pos_indices(), these indices address the complete qpos vector accepted byset_state_tensor(), including any root coordinates. Manager reset transactions resolve them on the cold path.
- get_joint_state_qvel_indices(names)[source]¶
Resolve single-DoF joints to full
set_state_tensorqvel columns.
- get_scene_layout()[source]¶
Return the immutable materialized public addresses, never native handles.
- Return type:
CompiledSceneLayout
- get_entity_state(entity)[source]¶
Return detached root_pose/root_velocity/joint_positions/joint_velocities.
Root fields follow EntityStatePatch’s link-origin/world-frame contract. Non-root joint fields use the frozen entity joint order and native generalized widths. Unavailable fields must fail, never return old data as if current. State freshness follows the adapter’s declared profile.
- get_entity_default_state(entity, env_ids=None)[source]¶
Detached construction/keyframe defaults in selected environment order.
Fields and frames match get_entity_state. Defaults follow immutable variant assignment and never reflect current reset-time randomization. This query does not reset, step or reparse the scene.
- reset_entities(request)[source]¶
Validate the complete selected-entity request, then commit it once.
Validation failure leaves all state unchanged. A native partial commit failure must fault the backend unless the adapter can actually roll back. Unselected entities/environments and fixed identity remain unchanged.
- get_dr_capabilities()[source]¶
Declare only the per-env round-trip-measured DR items (REPORT §5.7).
Portable mode maps the measured mass, COM, DOF-property and PD-gain terms through audited independent entities. Non-portable mode also declares the solver-level external-force API. Absolute geom_friction randomization remains unsupported because Genesis exposes only a per-env ratio API.
- Return type:
DomainRandomizationCapabilities
- apply_interval_randomization(plan)[source]¶
Apply a scheduled interval randomization plan.
Generic dispatch: each op yielded by
plan.iter_ops()is validated against the builtin term specs (custom terms pass through) and routed to the backend-owned handler table returned by_interval_term_handlers(). Op payloads are torch-first: Torch tensors orTensorIntervalPayloadvalues produced by the caller; host adapters convert tensors at their private boundary throughunisim.dr._host, and a missing producer-sampled payload fails closed. A term without a handler fails closed withNotImplementedErrornaming the backend class and the term. Backends that need per-plan prologue/epilogue semantics (for example clearing staged external forces before the ops accumulate) keep a thin override that calls this base implementation.- Parameters:
plan (
IntervalRandomizationPlan)- Return type:
- apply_body_force(body_ids, force, torque=None)[source]¶
Apply a world-frame wrench at each body COM for the upcoming step.
- resolve_play_render_plan(*, play_render_mode, play_steps, output_video)[source]¶
Resolve high-level playback mode into backend-owned render parameters.
- bind_renderer(spacing=1.0, *, offset_mode='grid', headless=False, capture=False, width=1280, height=720, camera_kwargs=None)[source]¶
Lazily attach the Genesis viewer and/or an offscreen camera.
Both are post-build attachments (verified on 1.3.3): the interactive viewer is a
genesis.vis.viewer.Viewerbuilt on the visualizer’s shared context; capture uses a visualizer camera built on demand.spacing/offset_modeare accepted for contract parity and ignored: envs are laid out on the Genesis scene’s own grid. The first (headless, capture) pair is pinned, like the isaacgym backend.
- capture_video_frame()[source]¶
Capture one offscreen RGB frame (self-initializes headless+capture).
- Return type:
- run_playback(*, env, initialize, step, num_steps, output_video=None, render_spacing=None, render_offset_mode=None, headless=None, record_video=None, frame_state_getter=None, camera_kwargs=None, debug_overlay_getter=None, on_frame=None)[source]¶
Execute backend-owned playback for an env wrapper.
camera_kwargsis normalized intoCameraCfgat this boundary; unknown mapping keys fail closed with an error naming them.debug_overlay_getteris an optional per-frame callback returning a sequence with one entry per environment (len == num_envs); each entry is that env’s sequence ofDebugPrimitive(Noneor empty marks an env without overlay) and returningNonedisables overlays for the frame. Primitive poses are env-local; the renderer applies grid offsets when composing multiple envs. Backends whoseget_play_capabilities().supports_debug_overlayis False fail closed withNotImplementedErrorwhen this is notNone. On the interactive rendering path only backends whosesupports_interactive_debug_overlayis True consume it; the others fail closed withNotImplementedError.on_frameis an optional per-frame video hook called by offline render pipelines before encoding: it receives(frame_index, frame)with the frame an(H, W, 3)uint8 array, and returns a replacement frame of the same shape/dtype orNoneto keep the original. Backends rendering through a native (non-offline) renderer fail closed withNotImplementedErrorwhen this is notNone.Known boundary:
envis the owning env wrapper, not a physics-layer concept. Current playback implementations read env-level configuration (e.g.cfg.scene,cfg.ctrl_dt,cfg.render_spacing) and env-owned playback helpers (get_playback_model,get_physics_state_snapshot) that have no backend-native equivalent yet. The parameter stays on this contract until playback asset/config resolution moves onto backend-owned metadata; backends must only use it on the cold playback path.
- get_play_capabilities()[source]¶
Return backend-native play/render capabilities.
- Return type:
PlayCapabilities
- get_physics_state_layout()[source]¶
Return the
[time, qpos, qvel]snapshot layout (no mocap tail yet).- Return type:
PhysicsStateLayout
- get_physics_state()[source]¶
Assemble contract
[time, qpos, qvel]rows in MJCF order.The host caches already hold the public layout: whole-MJCF scenes are validated against the source MJCF joint order at materialize time (
_validate_non_portable_joint_order()) and portable caches are scattered into the composed-scene column order; Genesis free-base and ball-joint quaternions are natively wxyz, matching MuJoCo. The time column is the backend accumulator advanced bynsteps * sim_dton every public step path and zeroed on state resets.- Return type:
- get_playback_model(env_index=None)[source]¶
Return the MJCF file path used by detached MuJoCo playback.
Whole-MJCF scenes replay through their (fragment-expanded) construction source and portable scenes through the composed MJCF. Portable fixed-variant scenes with more than one materialized source follow the Drake/Motrix contract: an explicit
env_indexis required and the row’s assigned variant scene file is returned.
- close()[source]¶
End the process-wide Genesis session; re-init afterwards fails closed.
- Return type:
- bind_height_scanner(*, hfield_geom_id, offsets, frame_body_id, alignment='yaw', output='height')¶
Create a reusable height-field scanner on the init/cold path.
Backends that support height-field terrain scan must override this method.
- bind_host_bridge_io(spec)¶
Compile a persistent transfer plan for a declared host bridge.
- Parameters:
spec (
TensorIOSpec)- Return type:
HostBridgeTransferPlan
- bind_mocap_pose(body_name)¶
Resolve a mocap body once; unavailable capabilities fail at binding.
- Parameters:
body_name (
str)- Return type:
MocapPoseBinding
- bind_sensor_data(names)¶
Materialize a validated view over named tensor sensors.
This cold-path binding records the flattened public view width and delegates execution to the backend-owned tensor sensor reader. It never falls back to a NumPy named-sensor getter.
- property capability_flags¶
Coarse capability labels for clients that need a cheap feature check.
The detailed contract is expressed by the methods on this class. The labels remain useful for benchmark/conformance metadata and are derived from the mandatory lifecycle methods rather than maintained separately by every adapter.
- get_body_id(name)¶
Resolve one body/link name through the backend contract.
- get_body_subtree_ids(root_body_id)¶
Return body ids in the subtree rooted at
root_body_id.
- get_capabilities(*, profile='default')¶
Query semantic declarations plus authoritative DR/play/variant support.
This cold-path query does not discover SDKs or verify runtime behavior. Materialized configuration readback is exposed by
get_import_report.- Parameters:
profile (
str)- Return type:
CapabilityReport
- get_import_report()¶
Return a detached construction/materialization configuration snapshot.
This cached report never parses assets, starts workers, or reflects reset-time randomization. Use current-property queries for live values.
- Return type:
ImportReport
- get_playback_mocap_state(env_index=0)¶
Return copied
(mocap_pos, mocap_quat)arrays for detached playback.Shapes are
(nmocap, 3)and(nmocap, 4)for the selected environment. Backends exposing this declareget_play_capabilities().supports_mocap_playback.
- get_scene_visual_model_file()¶
Return the scene visual model file on the cold path, when available.
Backends without a separate visual scene model return
None.
- get_site_ids(names)¶
Resolve site names to integer ID arrays.
- get_site_jacobian_w(site_id, dof_indices)¶
Compute world-frame Jacobians for one site and selected DoF columns.
- get_tensor_runtime_diagnostics()¶
Return runtime-selected diagnostics for optional tensor optimizations.
Unlike capability negotiation, these values describe actual cold-path initialization results and may change when a backend falls back or closes. The default empty mapping means the backend declares no optional tensor-runtime optimization.
- get_terrain_spawn_data()¶
Return backend-materialized terrain metadata on the cold path.
Backends without generated terrain support return
None. Callers should resolve this once during env initialization and cache the returned height-sampling callable for reset/reward hot paths.- Return type:
TerrainSpawnData|None
- get_tracked_body_views(body_names=None, device=None)¶
Return all tracked-body fields in one public backend read.
body_namesselects and orders the returned body axis.Nonerequests every tracked body in backend insertion order. This aggregate contract avoids one Python projection boundary per body/field sensor.
- set_mocap_pose_tensor(body_name, env_indices, poses)¶
Write selected mocap poses through the declared tensor lifecycle.
- set_pre_step_control(fn)¶
Register an env-owned policy-control to physics-control converter.
The callback receives
(backend, ctrl)so owner code can read the backend’s freshly-updated sensor contract before every physics substep. It must return either backend-native actuator control with the same shape, or aPreStepControlOutputcarrying that control plus an optional per-substep body wrench. A returned wrench is recomposed from scratch every substep and cleared when thestep()call finishes. Position-actuator envs leave this unset and keep the direct control path.
- backend_type: str¶