Adding a constraint with min_ and MVars in Python
回答済みI am looking to implement a constraint such as the following:
x = m.addMVar((100, 1), vtype=gp.GRB.CONTINUOUS)
y = m.addMVar((100, 1), vtype=gp.GRB.CONTINUOUS)
params = np.ones(y.shape)
m.addConstr(x == gp.min_(params, y))
The intended result is that each element i follows x[i] = min(params[i], y[i]) as a constraint. However, I get the error "ValueError: can only convert an array of size 1 to a Python scalar" which I am guessing is due to the fact that I am using MVars in the min_() function.
Please can you help me with a method of achieving this? One thing to note is it isn't feasible to loop over indices in the MVars as they are long and this takes too much time.
Thank you!
-
Hi Ben,
I would manually implement the min function. This involves introducing a binary variable for each x variable:
b = m.addMVar(x.shape, vtype=gp.GRB.BINARY)
then introducing the following constraints:
m.addConstr(x <= params)
m.addConstr(x <= y)
m.addConstr(x >= y - y_ub*b)
m.addConstr(x >= params*b)where v_ub is an array of upper bounds on the y variables. You should aim to make these upper bounds as tight as possible to improve performance.
Also consider whether there is naturally "upwards pressure" on the x variables, i.e. will they always take the largest value they can in an optimal solution? If so then you only need the first two constraint families.
Also note since params is constant you could alternatively enforce the first constraints in the variable definition and this may save some time:
x = m.addMVar((100, 1), ub=params, vtype=gp.GRB.CONTINUOUS)
You would of course need to define params before x to use this approach.
- Riley
0 -
Hi Riley,
Thank you for your reply, I've implemented this and its working. For my problem there is "downwards pressure" so the lower bound is important but this 4-constraint formulation is great for that.
Best,
Ben0
サインインしてコメントを残してください。
コメント
2件のコメント