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=&#039;BFGS&#039;).x
print(x_opt)
constraints = [dict(type=&#039;ineq&#039;, fun=g)]
x_cons_opt = minimize(f, (0, 0), method=&#039;SLSQP&#039;, constraints=constraints).x 
print(x_cons_opt)
x_cons_opt = minimize(f, (0, 0), method=&#039;COBYLA&#039;, 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], &#039;b<em>&#039;, markersize=15)
ax. Plot(x_, 1.75 + (x_-0.75)<strong>4, &#039;k-&#039;, markersize=15)
ax.fill_between(x_, 1.75 + (x_-0.75)</strong>4, 3, color=&quot;grey&quot;)
ax.plot(x_cons_opt[0], x_cons_opt[1], &#039;r</em>&#039;, markersize=15)
ax.set_ylim(-1, 3)
ax.set_xlabel(r&quot;$x_0$&quot;, fontsize=18)
ax.set_ylabel(r&quot;$x_1$&quot;, fontsize=18)
ax.set_title(&quot;Optimization with constraints&quot;)
plt.colorbar(c, ax=ax)
fig.tight_layout()
plt.savefig(&quot;example22.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