Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use OR(disjunction) constraint in gurobi ? #404

Closed
l-outsider opened this issue May 6, 2021 · 2 comments
Closed

How to use OR(disjunction) constraint in gurobi ? #404

l-outsider opened this issue May 6, 2021 · 2 comments

Comments

@l-outsider
Copy link

I have 10 variables(v0, v1, v2, ..., v9), and be outputed from handwritten digit recognition. They are in range [0, 1].

now i need a Vmodel, and variables satisify the following constraints:

v0 >= v7 || v1>=v7 || v2>=v7 || v3>=v7 || v4>=v7 || v5>=v7 || v6>=v7 || v8>=v7 || v9>=v7

how can i use model.addConstr() to add this OR constraint ?

@odow
Copy link
Member

odow commented May 6, 2021

  1. Use the C API

    function GRBgetgenconstrOr(model, genconstr, resvarP, nvarsP, vars)
    ccall((:GRBgetgenconstrOr, libgurobi), Cint, (Ptr{GRBmodel}, Cint, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), model, genconstr, resvarP, nvarsP, vars)
    end

  2. Reformulate as a MIP:

k = 7
model = Model(Gurobi.Optimizer)
@variable(model, 0 <= v[0:9] <= 1)
@variable(model, z[0:9], Bin)
for i in 0:9
    if i == k
        fix(z[k], 1.0)
    end
    @constraint(model, v[i] + z[i] >= v[k])
end
@constraint(model, sum(z) <= length(z) - 1)

@l-outsider
Copy link
Author

@odow
thank you, I sloved this problem by a simple way.

first, create additional 9 binary Vars[9].

then use GenConstrIndicator

for i in range:
    model.addConstr((Vars[i] == 1) >> v[i] >= v[7])

then add constr

model.addConstr(quicksum(Vars) >= 1)
model.addConstr(quicksum(Vars) <= 9)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants