Search code examples
pythonoptimizationerror-handlingcplexpyomo

TypeError: Cannot treat the value '<function objective_rule at 0x0000000007C31D08>' as a constant because it has unknown type 'function'


Team Pyomo, I kindly need help with the above-stated error. I have done everything I could, but still can't get my model to work. Below is the formulation of my 'Objective Function', and the errors message. Thank you.

## Define Objective ##
def objective_rule(model):
    s1=sum(1000*(model.fmax[j] - model.fmin[j])+ model.cmax[j] - model.cmin[j] for j in model.j)
    s2=sum(model.x[i,k]*model.k*model.t[i] for k in model.k for i in model.i)
    return s1 + 300 * s2
model.objective = Objective(expr=objective_rule, sense=minimize, doc='the objective function')

all the code that is before the objective function is fine (no errors). So, I will include below the code that comes after...it may be the one that caused the problem

## Display of the output ##
def pyomo_postprocess(options=None, instance=None, results=None):
    instance.x.display()
    writer = ExcelWriter("Data/output!G5:AJ27.csv")
    df.to_excel(writer,index=False)
    writer.save()

# pyomo command-line
if __name__ == '__main__':
    # This emulates what the pyomo command-line tools does
    from pyomo.opt import SolverFactory
    import pyomo.environ
    instance = model.create_instance()
    instance.pprint()
    opt = solvers.SolverFactory("cplex")
    results = opt.solve(instance, tee=True)
    # sends results to stdout
    instance.solutions.load_from(results)
    print("\nDisplaying Solution\n" + '-' * 60)
    pyomo_postprocess(None, instance, results)

When I execute the program, I have the next error message:

ERROR: Constructing component 'objective' from data=None failed:
    TypeError: Cannot treat the value '<function objective_rule at
    0x0000000007C31D08>' as a constant because it has unknown type
    'function'

Solution

  • The problem is that you're using the wrong keyword argument in your Objective component declaration. You should be using rule not expr:

    model.objective = Objective(rule=objective_rule, sense=minimize, doc='the objective function')
    

    The expr keyword is typically used when you have a very simple objective function expression and want to avoid writing a Python function to return the objective expression. You would use it like:

    model.objective = Objective(expr=m.x**2+m.y**2, sense=minimize, doc='the objective function')