Boolean comparison of decision variable with parameter
AnsweredHello, I want to create a sort of indicator function to use in my objective function. Here is the set up:
I have x_i for i from 1 to 10 as my decision variables. I have a list of lists (let's call it y, with one of these lists being called y_r) as an input; for example, 100 lists of 10 numbers, which are all randomly generated decision variables for which I have to compare my solution. If x_i is larger than y_r_i, I add a certain value v_i to my objective value. Else, I add 0.
This is my current code (r is given in this function):
gb.quicksum(v[i]*x[i] if x[i] > y[r][i] else 0 for i in range(10))
The error I get is:
TypeError: '>' not supported between instances of 'Var' and 'int'
i.e. due to x[i] being a decision variable in my Gurobi model and y[r][i] being an input integer.
How can I make this objection function work?
Kind regards,
Mike
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hello Mike,
The modelling approach will depend on whether you want to minimize or maximize your objective.
For example, if you want to maximize, with r fixed, and v's being non-negative, to build something like
> gb.quicksum(v[i]*x[i] if x[i] >= y[r][i] else 0 for i in range(10))
or essentially, for simplicity dropping sub-index r, add terms of the form
v[i]*x[i] if x[i] >= y[i]
one can use the so-called semi-continuous variables construct, see here https://www.gurobi.com/documentation/9.0/refman/variables.html
Then you can introduce an auxiliary semi-continuous z[i] with lower bound y[i] and upper bound GRB.INFINITY, unconditionally add the term
(*) v[i] * z[i]
to the objective, and add a constraint
(**) x[i] >= z[i]
Note if x[i] ends up smaller than y[i], due to (**) and z[i] being semi-continuous, z will take value 0 making no contribution to the objective. On the other hand, if x[i] ends up greater or equal than y[i], due to maximizing the objective and (**) you will essentially be adding v[i]*x[i] to the objective function.
Hope this helps.
0
Post is closed for comments.
Comments
2 comments