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

在Drake中编写LeafSystem时,能否从同一函数设置多个输出?

问题:将单个函数的多向量结果输出到不同端口

我想把单个函数计算得到的多个向量结果,输出到同一个LeafSystem的不同输出端口。最初写了如下代码,但无法正常工作:

class TestSplit(LeafSystem):
    def __init__(self):
        LeafSystem.__init__(self)
        self.DeclareVectorOutputPort('port-1', BasicVector(1), self.SetOutputReference)
        self.DeclareVectorOutputPort('port-2', BasicVector(1), self.SetOutputReference)

    def SetOutputReference(self, context, output):
        res1, res2 = foo()
        self.GetOutputPort("port-1").set_value(res1)
        self.GetOutputPort("port-2").set_value(res2)

我知道可以先把res1和res2拼接成一个向量输出,再用Demultiplexer在图中拆分,但想了解有没有直接设置的方法。


可行实现方式:利用缓存复用计算结果

通过声明缓存条目,让单个计算函数只执行一次,然后将结果分发给不同的输出端口,代码如下:

class Option4(LeafSystem):
    """从单个CalcSumDiff函数生成两个输出端口。
    方案4使用缓存机制,让CalcOutput复用CalcAddSub辅助函数计算得到的结果元组。
    """

    def __init__(self):
        LeafSystem.__init__(self)
        self._pair = self.DeclareVectorInputPort("pair", BasicVector(2))
        self._add_sub = self.DeclareCacheEntry(
            description="add_sub",
            value_producer=ValueProducer(
                allocate=lambda: AbstractValue.Make(tuple()),
                calc=self.CalcAddSub),
            prerequisites_of_calc={self._pair.ticket()})
        self.DeclareVectorOutputPort(
            "add", BasicVector(1), partial(self.CalcOutput, port_index=0),
            prerequisites_of_calc={self._add_sub.ticket()})
        self.DeclareVectorOutputPort(
            "sub", BasicVector(1), partial(self.CalcOutput, port_index=1),
            prerequisites_of_calc={self._add_sub.ticket()})

    def CalcAddSub(self, context, output):
        u = self.GetInputPort("pair").Eval(context)
        add = np.array([u[0] + u[1]])
        sub = np.array([u[0] - u[1]])
        output.set_value((add, sub))

    def CalcOutput(self, context, output, port_index):
        y0, y1 = self._add_sub.Eval(context)
        if port_index == 0:
            output.set_value(y0)
        if port_index == 1:
            output.set_value(y1)

内容的提问来源于stack exchange,提问作者corehammer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:45:16