FEMEntity(FEM 实体)#
- class genesis.engine.entities.fem_entity.FEMEntity(scene, solver, material, morph, surface, idx, v_start=0, el_start=0, s_start=0, vvert_start=0, vface_start=0, name: str | None = None)[source]#
Bases:
EntityA finite element method (FEM)-based entity for deformable simulation.
This class represents a deformable object using tetrahedral elements. It interfaces with the physics solver to handle state updates, checkpointing, gradients, and actuation for physics-based simulation in batched environments.
- Parameters:
scene (Scene) – The simulation scene that this entity belongs to.
solver (Solver) – The physics solver instance used for simulation.
material (Material) – The material properties defining elasticity, density, etc.
morph (Morph) – The morph specification that defines the entity’s shape.
surface (Surface) – The surface mesh associated with the entity (for rendering or collision).
idx (int) – Unique identifier of the entity within the scene.
v_start (int, optional) – Starting index of this entity’s vertices in the global vertex array (default is 0).
el_start (int, optional) – Starting index of this entity’s elements in the global element array (default is 0).
s_start (int, optional) – Starting index of this entity’s surface triangles in the global surface array (default is 0).
vvert_start (int, optional) – Starting index of this entity’s render vertices in the global render vertex array (default is 0).
vface_start (int, optional) – Starting index of this entity’s render faces in the global render face array (default is 0).
- set_position(pos)[source]#
Set the target position(s) for the FEM entity.
- Parameters:
pos (torch.Tensor or array-like) – The desired position(s). Can be: - (3,): a single COM offset vector. - (n_vertices, 3): per-vertex positions for all vertices. - (n_envs, 3): per-environment COM offsets. - (n_envs, n_vertices, 3): full batched per-vertex positions.
- Raises:
Exception – If the tensor shape is not supported.
- set_velocity(vel)[source]#
Set the target velocity(ies) for the FEM entity.
- Parameters:
vel (torch.Tensor or array-like) – The desired velocity(ies). Can be: - (3,): a global velocity vector for all vertices. - (n_vertices, 3): per-vertex velocities. - (n_envs, 3): per-environment velocities broadcast to all vertices. - (n_envs, n_vertices, 3): full batched per-vertex velocities.
- Raises:
Exception – If the tensor shape is not supported.
- set_actuation(actu)[source]#
Set the actuation signal for the FEM entity.
- Parameters:
actu (torch.Tensor or array-like) – The actuation tensor. Can be: - (): a single scalar for all groups. - (n_groups,): group-level actuation. - (n_envs, n_groups): batch of group-level actuation signals.
- Raises:
Exception – If the tensor shape is not supported or per-element actuation is attempted.
- set_muscle(muscle_group=None, muscle_direction=None)[source]#
Set the muscle group and/or muscle direction for the FEM entity.
- Parameters:
muscle_group (torch.Tensor or array-like, optional) – Tensor of shape (n_elements,) specifying the muscle group ID for each element.
muscle_direction (torch.Tensor or array-like, optional) – Tensor of shape (n_elements, 3) specifying unit direction vectors for muscle forces.
- Raises:
AssertionError – If tensor shapes are incorrect or normalization fails.
- instantiate(verts, elems)[source]#
Initialize FEM entity with given vertices and elements.
- Parameters:
verts (np.ndarray) – Array of vertex positions with shape (n_vertices, 3).
elems (np.ndarray) – Array of elements indexing into verts: tetrahedra with shape (n_elements, 4), or surface triangles with shape (n_elements, 3) for Cloth material.
- Raises:
Exception – If no vertices are provided.
- sample()[source]#
Build the entity’s visual geoms and simulation mesh from its morph.
Each morph sub-mesh becomes a visual geom with its own surface and UVs, while the simulation operates on a single welded copy of their vertices, tracked through ‘FEMVisGeom.sim_verts_idx’: welding and tetrahedralization both keep the input vertices first and in order, so these maps remain valid indices into the simulated vertices.
- compute_pressure_field()[source]#
Compute the pressure field for the FEM entity based on its tetrahedral elements.
For hydroelastic contact: https://drake.mit.edu/doxygen_cxx/group__hydroelastic__user__guide.html
Notes
RobotLocomotion/drake TODO: Add margin support Drake’s implementation of margin seems buggy.
- init_tgt_keys()[source]#
Initialize the keys used in target state management.
This defines which physical properties (e.g., position, velocity) will be tracked for checkpointing and buffering.
- init_tgt_vars()[source]#
Initialize the target state variables and their buffers.
This sets up internal dictionaries to store per-step target values for properties like velocity, position, actuation, and activation.
- init_ckpt()[source]#
Initialize the checkpoint storage dictionary.
Creates an empty container for storing simulation checkpoints.
- save_ckpt(ckpt_name)[source]#
Save the current target state buffers to a named checkpoint.
- Parameters:
ckpt_name (str) – The name to identify the checkpoint.
Notes
After saving, the internal target buffers are cleared to prepare for new input.
- load_ckpt(ckpt_name)[source]#
Load a previously saved target state buffer from a named checkpoint.
- Parameters:
ckpt_name (str) – The name of the checkpoint to load.
- Raises:
KeyError – If the checkpoint name is not found.
- process_input(in_backward=False)[source]#
Push position, velocity, and activation target states into the simulator.
- Parameters:
in_backward (bool, default=False) – Whether the simulation is in the backward (gradient) pass.
- Returns:
inputs – The inputs applied at this step, of any type, for the simulator to tape.
- Return type:
tuple
- process_input_grad()[source]#
Process gradients of input states and propagate them backward.
- Returns:
inputs_grad – The pairs (input, gradient) of the inputs applied at this step that track gradients.
- Return type:
list of tuple
Notes
Clears the gradients in the solver to avoid double accumulation.
- set_pos(f, pos)[source]#
Set element positions in the solver.
- Parameters:
f (int) – Current substep/frame index.
pos (torch.Tensor) – Tensor of shape (n_envs, n_vertices, 3) containing new positions.
- set_pos_grad(f, pos_grad)[source]#
Set gradient of element positions in the solver.
- Parameters:
f (int) – Current substep/frame index.
pos_grad (torch.Tensor) – Tensor of shape (n_envs, n_vertices, 3) containing gradients of positions.
- set_vel(f, vel)[source]#
Set element velocities in the solver.
- Parameters:
f (int) – Current substep/frame index.
vel (torch.Tensor) – Tensor of shape (n_envs, n_vertices, 3) containing velocities.
- set_vel_grad(f, vel_grad)[source]#
Set gradient of element velocities in the solver.
- Parameters:
f (int) – Current substep/frame index.
vel_grad (torch.Tensor) – Tensor of shape (n_envs, n_vertices, 3) containing gradients of velocities.
- set_actu(f, actu)[source]#
Set actuation values for elements in the solver.
- Parameters:
f (int) – Current substep/frame index.
actu (torch.Tensor) – Tensor of shape (n_envs, n_groups) specifying actuation values.
- set_actu_grad(f, actu_grad)[source]#
Set gradient of actuation values in the solver.
- Parameters:
f (int) – Current substep/frame index.
actu_grad (torch.Tensor) – Tensor of shape (n_envs, n_groups) specifying gradients of actuation.
- set_active(f, active)[source]#
Set the active status of each element.
- Parameters:
f (int) – Current substep/frame index.
active (int) – Activity flag (gs.ACTIVE or gs.INACTIVE).
- set_muscle_group(muscle_group)[source]#
Set muscle group index for each element.
- Parameters:
muscle_group (torch.Tensor) – Tensor of shape (n_elements,) specifying muscle group IDs.
- set_muscle_direction(muscle_direction)[source]#
Set muscle force direction for each element.
- Parameters:
muscle_direction (torch.Tensor) – Tensor of shape (n_elements, 3) with unit direction vectors.
- set_vertex_constraints(verts_idx_local, target_poss=None, link=None, is_soft_constraint=False, stiffness=0.0, envs_idx=None)[source]#
Set vertex constraints for specified vertices.
- Parameters:
verts_idx_local (array_like) – List of local vertex indices to constrain.
target_poss (array_like, shape (len(verts_idx), 3), optional) – List of target positions [x, y, z] for each vertex. If not provided, the initial positions are used.
link (RigidLink) – Optional rigid link for the vertices to follow, maintaining relative position.
is_soft_constraint (bool) – By default, use a hard constraint directly sets position and zero velocity. A soft constraint uses a spring force to pull the vertex towards the target position.
stiffness (float) – Specify a spring stiffness for a soft constraint. Critical damping is applied.
envs_idx (array_like, optional) – List of environment indices to apply the constraints to. If None, applies to all environments.
- update_constraint_targets(verts_idx_local, target_poss, envs_idx=None)[source]#
Update target positions for existing constraints.
- remove_vertex_constraints(verts_idx_local=None, envs_idx=None)[source]#
Remove constraints from the specified vertices and environments, or from all of them if None.
- get_el2v()[source]#
Retrieve the element-to-vertex mapping.
- Returns:
el2v – Tensor of shape (n_elements, 4) mapping each element to its local vertex indices.
- Return type:
torch.Tensor
- get_frame(f: <quadrants._lib.core.quadrants_python.DataTypeCxx object at 0x7b713aa45090>, pos: NdarrayType(dtype=None, ndim=None, layout=0, needs_grad=None), vel: NdarrayType(dtype=None, ndim=None, layout=0, needs_grad=None), active: NdarrayType(dtype=None, ndim=None, layout=0, needs_grad=None))[source]#
Fetch the position, velocity, and activation state of the FEM entity at a specific substep.
- Parameters:
f (int) – The substep/frame index to fetch the state from.
pos (np.ndarray) – Output array of shape (n_envs, n_vertices, 3) to store positions.
vel (np.ndarray) – Output array of shape (n_envs, n_vertices, 3) to store velocities.
active (np.ndarray) – Output array of shape (n_envs, n_elements) to store active flags.
- clear_grad(f: <quadrants._lib.core.quadrants_python.DataTypeCxx object at 0x7b713aa45090>)[source]#
Zero out the gradients of position, velocity, and actuation for the current substep.
- Parameters:
f (int) – The substep/frame index for which to clear gradients.
Notes
This method is primarily used during backward passes to manually reset gradients that may be corrupted by explicit state setting.
- property n_vertices#
Number of vertices in the FEM entity.
- property vgeoms#
The list of visual geoms (
FEMVisGeom) in the entity, one per morph sub-mesh.
- property n_elements#
surface triangles for Cloth material, tetrahedra otherwise.
- Type:
Number of simulation elements
- property n_surfaces#
Number of surface triangles extracted from the FEM mesh.
- property v_start#
Global vertex index offset for this entity.
- property el_start#
Global element index offset for this entity.
- property s_start#
Global surface triangle index offset for this entity.
- property n_vverts#
Number of render vertices in the FEM entity, summed over its visual geoms.
- property n_vfaces#
Number of render faces in the FEM entity, summed over its visual geoms.
- property vvert_start#
Global render vertex index offset for this entity.
- property vface_start#
Global render face index offset for this entity.
- property vvert_end#
Global render vertex index past this entity’s last one.
- property vface_end#
Global render face index past this entity’s last one.
- property n_surface_vertices#
Number of unique vertices involved in surface triangles.
- property surface_triangles#
Surface triangles of the FEM mesh.
- property tet_cfg#
Configuration of tetrahedralization.