import os
from scipy.optimize import minimize
import matplotlib.pyplot as plt
import numpy as np
os.chdir(r'D:\projects\wordpress\ex72')
os.getcwd()
def f(X):
x, y = X
return (x - 1)<strong>2 + (y - 1)</strong>2
def func_X_Y_to_XY(f, X, Y):
#Wrapper for f(X, Y) -> f([X, Y])
s = np.shape(X)
return f(np.vstack([X.ravel(), Y.ravel()])).reshape(*s)
x_opt = minimize(f, [1, 1], method='BFGS').x
bnd_x1, bnd_x2 = (2, 3), (0, 2)
x_cons_opt = minimize(f, [1, 1], method='L-BFGS-B', bounds=[bnd_x1, bnd_x2]).x
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_cons_opt[0], x_cons_opt[1], 'r</em>', markersize=15)
bound_rect = plt.Rectangle((bnd_x1[0], bnd_x2[0]),
bnd_x1[1] - bnd_x1[0], bnd_x2[1] -
bnd_x2[0], facecolor="grey")
ax.add_patch(bound_rect)
ax.set_xlabel(r"$x_1$", fontsize=14)
ax.set_ylabel(r"$x_2$", fontsize=14)
plt.colorbar(c, ax=ax)
fig.tight_layout()
plt.savefig("ex72.png", dpi=100)
plt.show()
plt.close()
Last Updated on 2024-07-14 by gantovnik

Recent Comments