Search code examples
pyomo

How to look-up constraint by number in a Pyomo model?


We are attempted to debug a Pyomo model. Ipopt with halt_on_ampl_error True tells up Error evaluating constraint 30. Is there an easy way to programmatically look up a constraint in a Pyomo model by its number (using the numbering of Ipopt)?


Solution

  • You can just modify your call to solve slightly:

    opt = SolverFactory('ipopt')
    res = opt.solve(model, symbolic_solver_labels=True)
    

    Then, you should see a more useful error message in the ipopt output.

    Let me extend this answer to address the other part of the question regarding looking up a constraint by its number. Because Pyomo variables and constraints do not have indices, this is very solver-interface-specific. For Pynumero, you have a couple of options. Suppose you have the following ConcreteModel called m and PyomoNLP called nlp.

    import pyomo.environ as pyo
    from pyomo.contrib.pynumero.interfaces.pyomo_nlp import PyomoNLP
    
    m = pyo.ConcreteModel()
    m.x = pyo.Var()
    m.y = pyo.Var()
    m.obj = pyo.Objective(expr=m.y)
    m.c1 = pyo.Constraint(expr=m.y >= m.x)
    m.c2 = pyo.Constraint(expr=m.y >= -m.x)
    
    nlp = PyomoNLP(m)
    

    If you just want to get the index of of a few variables or constraints, you can use

    var_indices = nlp.get_primal_indices([m.x, m.y])
    con_indices = nlp.get_constraint_indices([m.c1, m.c2])
    

    If you want complete maps both directions, you can use

    con_to_index = dict()
    index_to_con = dict()
    var_to_index = pyo.ComponentMap()
    index_to-var = dict()
    for ndx, var in enumerate(nlp.get_pyomo_variables()):
        var_to_index[var] = ndx
        index_to_var[ndx] = var
    for ndx, con in enumerate(nlp.get_pyomo_constraints()):
        con_to_index[con] = ndx
        index_to_con[ndx] = con