ex72

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) -&gt; f([X, Y])
    s = np.shape(X)
    return f(np.vstack([X.ravel(), Y.ravel()])).reshape(*s)

x_opt = minimize(f, [1, 1], method=&#039;BFGS&#039;).x
bnd_x1, bnd_x2 = (2, 3), (0, 2)
x_cons_opt = minimize(f, [1, 1], method=&#039;L-BFGS-B&#039;, 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], &#039;b<em>&#039;, markersize=15)
ax.plot(x_cons_opt[0], x_cons_opt[1], &#039;r</em>&#039;, 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=&quot;grey&quot;)
ax.add_patch(bound_rect)
ax.set_xlabel(r&quot;$x_1$&quot;, fontsize=14)
ax.set_ylabel(r&quot;$x_2$&quot;, fontsize=14)
plt.colorbar(c, ax=ax)
fig.tight_layout() 
plt.savefig(&quot;ex72.png&quot;, dpi=100) 
plt.show() 
plt.close()

 

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading