In [1]:
from lpfgopt import minimize
import matplotlib.pyplot as plt
# set up the objective funciton,
# constraint fuction and bounds
f = lambda x: sum([i**2 for i in x])
g = lambda x: -x[0]**2 + 10 - x[1]
bounds = [[-5,5] for i in range(2)]
# run the optimization
sol = minimize(f, bounds, fconstraint=g)['x']
print(f"Solution is: {sol}")
# plot the results on a contour plot
gg = lambda x: -x**2 + 10 # for plotting purposes
plt.figure(figsize=(8,8))
x, y = np.linspace(-5,5,1000), np.linspace(-5,5,1000)
X, Y = np.meshgrid(x,y)
Z = f([X,Y])
plt.contourf(X,Y,Z)
plt.plot(x, gg(x), "r", label="constraint")
plt.plot(*sol, 'x',
markersize=14,
markeredgewidth=4,
color="lime",
label="optimum")
plt.ylim(-5,5)
plt.xlim(-5,5)
plt.legend()
plt.show()
In [ ]: