You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Drake系统设置不同的输入与输出尺寸?

问题:从13维输入向量提取元素生成2维输出系统

我正尝试编写一个系统,输入为自由体的状态(13维向量),输出为旋转关节的期望状态(2维向量)。目前只想从输入状态中提取一个值,尝试了以下代码:

ball_state = Variable("ball_state")
desired_theta_system = builder.AddSystem(SymbolicVectorSystem(input=[ball_state], state=[], dynamics=[], output=[ball_state[6], 0]))

但运行失败,提示ball_state变量不可下标访问。请问该如何实现?是否需要派生LeafSystem?


解决方案

方法1:用SymbolicVectorSystem实现(简洁版)

Variable对象本身不支持下标访问,你需要先创建带维度的符号向量。使用MakeVectorVariable生成指定维度的符号向量后,就能正常通过索引提取元素,代码示例:

# 创建13维符号输入向量
ball_state = MakeVectorVariable(13, "ball_state")
# 定义输出:提取输入的第7个元素(索引6),第二个元素固定为0
desired_theta_system = builder.AddSystem(
    SymbolicVectorSystem(
        input=[ball_state],
        state=[],
        dynamics=[],
        output=[ball_state[6], 0.0]
    )
)

方法2:派生LeafSystem(灵活扩展版)

如果后续需要添加更复杂的逻辑处理,派生LeafSystem会更灵活。示例代码:

class DesiredThetaSystem(LeafSystem):
    def __init__(self):
        super().__init__()
        # 声明13维输入端口
        self.DeclareVectorInputPort("ball_state", BasicVector(13))
        # 声明2维输出端口并绑定计算函数
        self.DeclareVectorOutputPort(
            "desired_theta",
            BasicVector(2),
            self.CalcOutput
        )
    
    def CalcOutput(self, context, output):
        # 获取输入向量的具体值
        ball_state = self.GetInputPort("ball_state").Eval(context)
        # 设置输出内容:提取第7个元素,第二个元素设为0
        output.SetFromVector([ball_state[6], 0.0])

# 将自定义系统添加到builder中
desired_theta_system = builder.AddSystem(DesiredThetaSystem())

两种方案都能满足需求:仅需简单提取元素选方法1即可;若后续有复杂逻辑扩展需求,方法2更适配。

内容的提问来源于stack exchange,提问作者Tom C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:40:57