Search code examples
pythonmathematical-optimizationpyomo

Why is the objective object in my pyomo code have an unknown type 'generator'?


I am creating an optimisation problem with a myriad of constraints using the pyomo library in Python, but I continue to get an error in my seemingly simple Objective definition, and don't understand why.

I am creating an abstract model, where the objective is minimising the cost (ab_mdl.c) times the power (ab_mdl.x) for each hour (i) and each resource (j). Here is the objective function written below:

def TOU_rule(ab_mdl):
    return(summation(ab_mdl.c[i]*ab_mdl.x[j,i]) for i in ab_mdl.hours for j in ab_mdl.num_of_cars)

ab_mdl.cost_obj=Objective(rule=TOU_rule)

But, when I run the full code, I get this error:

Cannot treat the value '. at 0x21427670>' as a constant because it has unknown type 'generator'

I don't understand what exactly is wrong with the code, especially since this is relatively simple objective, and I have followed the syntax of similar examples I've seen using Pyomo. Does anyone have any ideas of what I should do next?


Solution

  • Maybe it is a typo in your question, but if it is not, I see 3 improvements that you should do to make your code work.

    1. The return(thing) statement should be written return thing. That is because return is a separated word and there is no use for a parenthesis.

    2. In the same line, summation is not the right word, you have to use sum.

    3. Don't forget to put an optimization sense (maximize or minimize) when calling to build your objective.

    Then, your code will be:

    def TOU_rule(ab_mdl): 
        return sum(ab_mdl.c[i]*ab_mdl.x[j,i]) for i in ab_mdl.hours for j in ab_mdl.num_of_cars
    ab_mdl.cost_obj=Objective(rule=TOU_rule, sense=minimize)