I have a networkX graph with few nodes and these nodes have attributes such as "demand".

def mygraph():
    G = nx.Graph()
    G.add_nodes_from([("N1", {"demand": 10}),
    ("N2"{"demand": 12}),
    ("N3", {"demand": 25}),
    ("N4"{"demand": 18})])

I want my Pyomo Abstract model to create constraints and decision variables dynamically. Like,

def mymodel():
    model = AbstractModel()
    g=mygraph() #mygraph passed to abstract model
    model.nodes_range = RangeSet(1,len(g))# this creates a parameter with same size of the graph
    model.C = Param(model.nodes_range, within=pyo.NonNegativeIntegers) #one parameter for each node

    def constraint_rule(model, i): #dummy constraint
         return sum(model.decision_var*demand_node1)<=something
    model.const1=Constraint(model.nodes_range, rule=constraint_rule)
    model.obj1 = Objective(my objective) #my dummy objective
    status = SolverFactory('glpk')
    results = status.solve(model)

But the model.const1.pprint() command is giving 0 constraints. Can you guide me with the logic?


1 Answer 1


You are missing a model.create_instance call to actually construct the abstract model into a concrete instance. Calling pprint on abstract model components will always return empty components because they haven't been constructed.

I don't see anything in your example model that would require an AbstractModel so you could also try using a ConcreteModel instead and then you could call pprint on components any time after declaration.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.