Skip to content

Instantly share code, notes, and snippets.

@mayataka
Last active August 5, 2022 13:58
Show Gist options
  • Save mayataka/808b375cc5ba4a5e48df4ed5ea4ef1c3 to your computer and use it in GitHub Desktop.
Save mayataka/808b375cc5ba4a5e48df4ed5ea4ef1c3 to your computer and use it in GitHub Desktop.
A very simple MILP via CasADi
from casadi import *
import numpy as np
# optimization variables
x1 = SX.sym('x1')
x2 = SX.sym('x2')
w = [x1, x2]
w0 = [0, 0]
lbw = [-np.inf, -np.inf]
ubw = [np.inf, np.inf]
discrete = [False, True]
# objective function
J = 8.0 * x1 + x2
# constraints
g = []
lbg = []
ubg = []
g += [x1 + 2 * x2]
lbg += [-14.0]
ubg += [np.inf]
g += [-4 * x1 - x2]
lbg += [-np.inf]
ubg += [-33.0]
g += [2 * x1 + x2]
lbg += [-np.inf]
ubg += [20.0]
# Concatenate decision variables and constraint terms
w = vertcat(*w)
g = vertcat(*g)
prob = {'f': J, 'x': w, 'g': g}
solver = nlpsol('solver', 'bonmin', prob, {"discrete": discrete})
# solver = nlpsol('solver', 'ipopt', prob)
sol = solver(x0=vertcat(*w0), lbx=lbw, ubx=ubw, lbg=lbg, ubg=ubg)
print('solution: ', sol['x'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment