如何获取compass_gait模型的离散状态与抽象状态?
Hey there! Let me walk you through how to get the discrete states and abstract states for the compass gait model in Drake—super straightforward once you know where to look.
The compass gait model stores both the stance toe position and support leg indicator in its discrete state vector. Here's how to pull them out:
1. Initialize the model and context
First, set up your CompassGait system and a default context (this is where all state data lives):
from pydrake.examples.compass_gait import CompassGait, CompassGaitParams # Use default parameters, or tweak them as needed params = CompassGaitParams() compass_gait = CompassGait(params) context = compass_gait.CreateDefaultContext()
2. Extract the discrete state elements
The discrete state vector has two key entries:
- Index 0: The stance toe position along the ramp (a numerical value)
- Index 1: The support leg indicator (stored as an integer:
1for left leg support,0for right)
You can access them like this:
# Grab the full discrete state vector discrete_state = context.get_discrete_state() # Extract stance toe position stance_toe_pos = discrete_state.GetAtIndex(0) print(f"Stance toe position: {stance_toe_pos:.3f}") # Convert the integer indicator to a boolean for readability is_left_support = bool(discrete_state.GetAtIndex(1)) print(f"Left leg is supporting? {is_left_support}")
If by "abstract state" you mean a high-level, human-readable representation of the support leg (like "left" vs "right"), you can build that on top of the discrete state value. For example, using an enum to make it more structured:
from enum import Enum # Define an enum for clear abstract state representation class SupportLeg(Enum): RIGHT = 0 LEFT = 1 # Map the discrete state integer to the enum current_support_leg = SupportLeg(int(discrete_state.GetAtIndex(1))) print(f"Current support leg: {current_support_leg.name}")
Tracking states during simulation
If you need to monitor these states as the simulation runs, just re-fetch the discrete state after advancing the simulator:
from pydrake.systems.analysis import Simulator # Set up the simulator simulator = Simulator(compass_gait, context) simulator.Initialize() # Advance simulation to a specific time simulator.AdvanceTo(0.5) # Get updated states updated_discrete_state = context.get_discrete_state() updated_support_leg = SupportLeg(int(updated_discrete_state.GetAtIndex(1))) print(f"After 0.5 seconds, support leg is: {updated_support_leg.name}")
A quick note: Drake stores discrete states as numerical values, so the boolean "left support" indicator is saved as 0 or 1—you just need a quick conversion to get the boolean or abstract representation you want.
内容的提问来源于stack exchange,提问作者Axebobby

