未连接输入的 OpenMDAO 可选错误

OpenMDAO Optional Error on Unconnected Input

如果给定的输入未连接,是否有任何方法可以强制 OpenMDAO 引发错误?我知道对于许多输入,可以提供默认值以便不需要连接输入,但是有没有办法告诉 OpenMDAO 在某些键输入未连接时自动引发错误?

从 V3.17 开始,这还没有内置到 OpenMDAO 中。但是,有可能做到这一点。唯一需要注意的是,我必须使用一些非 public API 才能使其工作(注意 p.model._conn_global_abs_in2out 的使用)。因此,这些 API 稍后可能会发生变化。

此代码应该可以为您提供所需的行为。如果您愿意,可以使用 variable tagging if you wanted a solution that didn't require you to give a list of variable names to the validate function. The list_inputs method can accept tags to filter by 来扩充内容。

import openmdao.api as om

def validate_connections(prob, force_connected):

    # make sure its a set and not a generic iterator (i.e. array)
    force_connected_set = set(force_connected)


    model_inputs = prob.model.list_inputs(out_stream=None, prom_name=True)

    #gets the promoted names from the list of inputs
    input_set = set([inp[1]['prom_name'] for inp in model_inputs])
    

    # filter the inputs into connected and unconnected sets
    connect_dict = p.model._conn_global_abs_in2out
    unconnected_inputs = set()
    connected_inputs = set()
    for abs_name, in_data in model_inputs: 
        if abs_name in connect_dict and (not 'auto_ivc' in connect_dict[abs_name]): 
            connected_inputs.add(in_data['prom_name'])
        else: 
            unconnected_inputs.add(in_data['prom_name'])

    # now we need to check if there are any unconnected inputs 
    # in the model that aren't in the spec
    illegal_unconnected = force_connected_set.intersection(unconnected_inputs)
    if len(illegal_unconnected) > 0:
        raise ValueError(f'unconnected inputs {illegal_unconnected} are are not allowed')


p = om.Problem()

###############################################################################################
# comment and uncomment these three lines to change the error you get from the validate method
###############################################################################################
# p.model.add_subsystem('c0', om.ExecComp('x=3*a'), promotes_outputs=['x'])
# p.model.add_subsystem('c1', om.ExecComp('b=a+17'))
# p.model.connect('c1.b', 'c2.b')

p.model.add_subsystem('c2', om.ExecComp('y=2*x+b'), promotes_inputs=['x'])
p.model.add_subsystem('c3', om.ExecComp('z=x**2+y'))

p.setup()
p.final_setup()

如果这是您认为应该添加到 OpenMDAO 中的功能,请随时提交 POEM proposing how a formal feature and its API might look