Andrew
Andrew

Reputation: 175

OpenMDAO Optional Error on Unconnected Input

Is there any way to force OpenMDAO to raise an error if a given input is unconnected? I know for many inputs, defaults can be provided such that the input doesn't need to be connected, however is there a way to tell OpenMDAO to automatically raise an error if certain key inputs are unconnected?

Upvotes: 0

Views: 51

Answers (1)

Justin Gray
Justin Gray

Reputation: 5710

This is not built into OpenMDAO, as of V3.17. However, it is possible to do it. The only caveat is that i had to use some non public APIs to make it work (notice the use of the p.model._conn_global_abs_in2out). So those APIs are subject to changer later.

This code should give you the behavior your want. You could augment things with the use of 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 instead if you prefer that.

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()

If this is a feature you think should be added to OpenMDAO proper, then feel free to submit a POEM proposing how a formal feature and its API might look.

Upvotes: 1

Related Questions