compute_partials 每次迭代的调用顺序

compute_partials call order per iteration

为了尽量减少每次迭代的重复计算次数,我在计算方法中使用了一些额外的 class 变量,这些变量也在 compute_partials() 中使用。

(看下面的代码片段,我的意思会很清楚。)

问题是;

有没有在 compute() 之前调用 compute_partials() 的情况。 使用类似于下面的代码的 compute() 和 compute_partials() 是否有任何风险(参见这两种方法)

class MomentOfInertiaComp(ExplicitComponent):

    def initialize(self):
        self.options.declare('num_elements', types=int)
        self.options.declare('b')
        self.compcou=0
        self.partcou =0

    def setup(self):
        num_elements = self.options['num_elements']

        self.add_input('h', shape=num_elements)
        self.add_output('I', shape=num_elements)

        rows = np.arange(num_elements)
        cols = np.arange(num_elements)
        self.declare_partials('I', 'h', rows=rows, cols=cols)

    def compute(self, inputs, outputs):
        b = self.options['b']

        # Instead of this line 
        # outputs['I'] = 1./12. * b * inputs['h'] ** 3

        # these 2 lines are used
        self.var=inputs['h'] ** 2
        outputs['I'] = 1./12. * b * inputs['h'] * self.var


        self.compcou += 1

    def compute_partials(self, inputs, partials):
        b = self.options['b']
        self.partcou += 1
        # instead of this 
        # partials['I', 'h'] = 1./4. * b * inputs['h'] ** 2
        # this is used
        partials['I', 'h'] = 1./4. * b * self.var

Openmdao 不保证在 compute_partials 之前调用计算。你需要假设它们是完全独立的。