Last active
November 2, 2022 23:38
-
-
Save hdavid16/a91aad7aeb219a51554cc588420affbf to your computer and use it in GitHub Desktop.
Visualizing an LP using JuMP and Polyhedra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using JuMP, HiGHS, Polyhedra, CDDLib, Plots | |
# solve LP | |
m = Model(HiGHS.Optimizer) | |
x, y = @variable(m, v[i=1:2], lower_bound = 0) | |
@constraint(m, c[i=1:4], [6,1,-1,0][i]*x + [4,2,1,1][i]*y ≤ [24,6,1,2][i]) | |
@objective(m, Max, x+y) | |
optimize!(m) | |
xopt, yopt = value.(v) | |
# visualize solution | |
g = range(0,5,200) | |
x,y = repeat(g',200,1), repeat(g,1,200) | |
obj = x .+ y | |
polygon = polyhedron(m, CDDLib.Library(:exact)) | |
fig = plot(polygon, color=:gray, alpha=0.3, xlabel="x", ylabel="y", xlim=(0,5), ylim=(0,3), label="feasible space") | |
# plot constraints | |
x0 = range(0,5,2000) | |
yvals = [6,3,1,2,0] .+ [-1.5,0.5,1,0,0] * x0' | |
labels = ["6x+4y≤24", "x+2y≤6", "-x+y≤1", "y≤2", "x≥0", "y≥0"] | |
for i in 1:5 | |
plot!(x0, yvals[i,:], label=labels[i], linewidth=2, legend=:topright, palette=:seaborn_bright) | |
end | |
plot!([0,0],[0,3], label=labels[end], linewidth=2) | |
for xv in points(polygon) | |
scatter!([xv[1]], [xv[2]], color=:black, markersize=5, label=nothing) | |
annotate!(xv[1]+0.1, xv[2]+0.1, ("($(float(xv[1])), $(float(xv[2])))", 10, :left)) | |
end | |
# objective contours | |
contour!(g,g,obj,levels=1:6,color=:hsv,clabels=true) | |
# optimal point | |
scatter!([xopt], [yopt], color=:orange, markersize=5, label=nothing) | |
savefig(fig, "plot.png") | |
fig |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment