FEMEntity(有限元法实体)#
- class genesis.engine.entities.fem_entity.FEMEntity(scene, solver, material, morph, surface, idx, v_start=0, el_start=0, s_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).
- 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 tetrahedral elements with shape (n_elements, 4), indexing into verts.
- Raises:
Exception – If no vertices are provided.
- sample()[source]#
Sample mesh and elements based on the entity’s morph type.
For Cloth material, loads surface mesh directly without tetrahedralization. For regular FEM materials, tetrahedralizes the mesh.
- Raises:
Exception – If the morph type is unsupported.
- 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.
- reset_grad()[source]#
Clear all stored gradient-related buffers.
This resets the target buffer and clears any queried states used for gradient tracking.
- 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.
- process_input_grad()[source]#
Process gradients of input states and propagate them backward.
Notes
Automatically applies the backward hooks for position, velocity, and actuation tensors. 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 (gs.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 (gs.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 (gs.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 (gs.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 (gs.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 (gs.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 specified vertices, or all if None.
- get_el2v()[source]#
Retrieve the element-to-vertex mapping.
- Returns:
el2v – Tensor of shape (n_elements, 4) mapping each element to its vertex indices.
- Return type:
gs.Tensor
- get_frame(f: <gstaichi._lib.core.gstaichi_python.DataTypeCxx object at 0x10917d0f0>, pos: NdarrayType(dtype=None, ndim=None, layout=Layout.AOS, needs_grad=None), vel: NdarrayType(dtype=None, ndim=None, layout=Layout.AOS, needs_grad=None), active: NdarrayType(dtype=None, ndim=None, layout=Layout.AOS, 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: <gstaichi._lib.core.gstaichi_python.DataTypeCxx object at 0x10917d0f0>)[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 n_elements#
Number of tetrahedral elements in the FEM entity.
- 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 morph#
Morph specification used to generate the FEM mesh.
- property material#
Material properties of the FEM entity.
- property surface#
Surface for rendering.
- property n_surface_vertices#
Number of unique vertices involved in surface triangles.
- property surface_triangles#
Surface triangles of the FEM mesh.
- property uvs#
UV coordinates for this entity’s vertices, or None if not available.
- property tet_cfg#
Configuration of tetrahedralization.