In [1]:
# Import PuLP modeler functions
from pulp import *
In [2]:
x = LpVariable('x', -10, 10)
y = LpVariable('y', -10, 10)
prob = LpProblem("Toy Problem", LpMinimize)
prob += 3*x - y
prob.solve()
Out[2]:
$$1$$
In [3]:
prob
Out[3]:
Toy Problem:
MINIMIZE
3*x + -1*y + 0
VARIABLES
-10 <= x <= 10 Continuous
-10 <= y <= 10 Continuous
In [4]:
(x.value(), y.value())
Out[4]:
$$\begin{pmatrix}-10.0, & 10.0\end{pmatrix}$$
In [5]:
from pylab import *
In [6]:
def obj(x,y):
    return 3*x - y
def add_constraint(cx, cy, c):
    # cx.x + cy.y = c
    # x = c - cy/cx . y
    # y = c - cx/cy . x
    if cy != 0:
        plot([LO, HI], [c - LO*cx/cy, c - HI*cx/cy])
    else:
        plot([c - LO*cy/cx, c - HI*cy/cx], [LO, HI] )
In [7]:
LO = -11
HI = 11
xx = yy = np.linspace(LO, HI)
XX,YY = np.meshgrid(xx,yy)
contourf(XX,YY,obj(XX,YY), 100)
xlim(LO, HI)
ylim(LO, HI)
xlabel('x')
ylabel('y')
add_constraint(1,0, 10)
add_constraint(1,0, -10)
add_constraint(0,1, -10)
add_constraint(0,1, 10)
plot(x.value(), y.value(), markersize=30,  marker='*')
colorbar()
Out[7]:
<matplotlib.colorbar.Colorbar instance at 0x537a488>
In [8]:
prob += (x+0.8*y >= 3), "extra constraint"
prob += (x-0.8*y <= -3), "c2"
In [9]:
#prob += (x-0.8*y == 3), "c3"
In [10]:
prob.solve()
Out[10]:
$$1$$
In [11]:
XX,YY = np.meshgrid(xx,yy)
contourf(XX,YY,obj(XX,YY), 100)
xlim(LO, HI)
ylim(LO, HI)
xlabel('x')
ylabel('y')
add_constraint(1,0.8,3)
add_constraint(1,-0.8,-3)

add_constraint(1,0,10)
add_constraint(1,0,-10)
add_constraint(0,1,-10)
add_constraint(0,1,10)
plot(x.value(), y.value(), markersize=30,  marker='*')
colorbar()
Out[11]:
<matplotlib.colorbar.Colorbar instance at 0x58bdcf8>
In [12]:
prob
Out[12]:
Toy Problem:
MINIMIZE
3*x + -1*y + 0
SUBJECT TO
extra_constraint: x + 0.8 y >= 3

c2: x - 0.8 y <= -3

VARIABLES
-10 <= x <= 10 Continuous
-10 <= y <= 10 Continuous
In [28]:
x.value(), y.value()
Out[28]:
$$\begin{pmatrix}-5.0, & 10.0\end{pmatrix}$$