#150 Optimization with a module in python

ex150.py

import os
import numpy as np
from scipy.optimize import minimize, Bounds
from structure import structure

os.chdir(r'D:\projects\wordpress\ex150')
os.getcwd()

def runoptimization(params,stressmax):
    
    objhist=[]
    
    def objcon(x):
        mass,stress=structure(x,params)
        f=mass
        g=stressmax-stress
        objhist.append(mass)
        return f,g

    xlast=[]
    flast=[]
    glast=[]

    def obj(x):
        nonlocal xlast,flast,glast
        if not np.array_equal(x,xlast):
            flast,glast = objcon(x)
            xlast = x
        return flast

    def con(x):
        nonlocal xlast,flast,glast
        if not np.array_equal(x,xlast):
            flast,glast = objcon(x)
            xlast=xlast
        return glast

    x0=[6.0,4.0]
    lb=[0.0,0.0]
    ub=[20.0,20.0]
    bounds=Bounds(lb,ub,keep_feasible=True)
    constraints = {'type': 'ineq','fun': con}
    options={'disp':True}
    res = minimize(obj,x0,constraints=constraints,options=options,bounds=bounds)
    print('x =',res.x)
    print('f =',res.fun)
    print(res.success)
    return res.x,res.fun,objhist

if __name__=="__main__":
    params=[100.0,3.0]
    stressmax=[1.0,5.0]
    
    xsta,fstar,objhist=runoptimization(params,stressmax)
    import matplotlib.pyplot as plt
    plt.figure()
    plt.semilogy(objhist)
    plt.xlabel('iter', fontsize=17)
    plt.ylabel('obj', fontsize=17)
    plt.savefig("ex150.png", dpi=100)
    plt.show()

structure.py:

import numpy as np
import time

def structure(x,params):
    mass = (1-x[0])**2 + 100*(x[1]-x[0]**2)**2
    stress = np.zeros(2)
    stress[0]=x[0]**2 + x[1]**2
    stress[1]=x[0] + params[1]*x[1]
    return mass,stress

Output:

Optimization terminated successfully    (Exit mode 0)
            Current function value: 0.04567573217474147
            Iterations: 24
            Function evaluations: 75
            Gradient evaluations: 24
x = [0.78644243 0.61766166]
f = 0.04567573217474147
True