import os
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
os.chdir(r'D:\data\scripts\web1\ex22')
os.getcwd()
def f(X):
return (X[0]-1)<strong>2 + (X[1]-1)</strong>2
def g(X):
return X[1]-1.75-(X[0]-0.75)**4
def func_X_Y_to_XY(f, X, Y):
s = np.shape(X)
return f(np.vstack([X.ravel(), Y.ravel()])).reshape(*s)
x_opt=minimize(f,(0,0),method='BFGS').x
print(x_opt)
constraints = [dict(type='ineq', fun=g)]
x_cons_opt = minimize(f, (0, 0), method='SLSQP', constraints=constraints).x
print(x_cons_opt)
x_cons_opt = minimize(f, (0, 0), method='COBYLA', constraints=constraints).x
print(x_cons_opt)
fig, ax = plt.subplots(figsize=(6, 4))
x_ = y_ = np.linspace(-1, 3, 100)
X, Y = np.meshgrid(x_, y_)
c = ax. Contour(X, Y, func_X_Y_to_XY(f, X, Y), 50)
ax. Plot(x_opt[0], x_opt[1], 'b<em>', markersize=15)
ax. Plot(x_, 1.75 + (x_-0.75)<strong>4, 'k-', markersize=15)
ax.fill_between(x_, 1.75 + (x_-0.75)</strong>4, 3, color="grey")
ax.plot(x_cons_opt[0], x_cons_opt[1], 'r</em>', markersize=15)
ax.set_ylim(-1, 3)
ax.set_xlabel(r"$x_0$", fontsize=18)
ax.set_ylabel(r"$x_1$", fontsize=18)
ax.set_title("Optimization with constraints")
plt.colorbar(c, ax=ax)
fig.tight_layout()
plt.savefig("example22.png", dpi=100)
plt.show()
plt.close()
Like this:
Like Loading...
Related
Recent Comments