{"id":847,"date":"2021-01-24T03:12:32","date_gmt":"2021-01-24T11:12:32","guid":{"rendered":"http:\/\/gantovnik.com\/bio-tips\/?p=847"},"modified":"2021-01-24T03:12:32","modified_gmt":"2021-01-24T11:12:32","slug":"150-optimization-with-a-module-in-python","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2021\/01\/150-optimization-with-a-module-in-python\/","title":{"rendered":"#150 Optimization with a module in python"},"content":{"rendered":"<p>#150 Optimization with a module in python<\/p>\n<p>ex150.py<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport os\r\nimport numpy as np\r\nfrom scipy.optimize import minimize, Bounds\r\nfrom structure import structure\r\n\r\nos.chdir(r'D:\\projects\\wordpress\\ex150')\r\nos.getcwd()\r\n\r\ndef runoptimization(params,stressmax):\r\n    \r\n    objhist=&#x5B;]\r\n    \r\n    def objcon(x):\r\n        mass,stress=structure(x,params)\r\n        f=mass\r\n        g=stressmax-stress\r\n        objhist.append(mass)\r\n        return f,g\r\n\r\n    xlast=&#x5B;]\r\n    flast=&#x5B;]\r\n    glast=&#x5B;]\r\n\r\n    def obj(x):\r\n        nonlocal xlast,flast,glast\r\n        if not np.array_equal(x,xlast):\r\n            flast,glast = objcon(x)\r\n            xlast = x\r\n        return flast\r\n\r\n    def con(x):\r\n        nonlocal xlast,flast,glast\r\n        if not np.array_equal(x,xlast):\r\n            flast,glast = objcon(x)\r\n            xlast=xlast\r\n        return glast\r\n\r\n    x0=&#x5B;6.0,4.0]\r\n    lb=&#x5B;0.0,0.0]\r\n    ub=&#x5B;20.0,20.0]\r\n    bounds=Bounds(lb,ub,keep_feasible=True)\r\n    constraints = {'type': 'ineq','fun': con}\r\n    options={'disp':True}\r\n    res = minimize(obj,x0,constraints=constraints,options=options,bounds=bounds)\r\n    print('x =',res.x)\r\n    print('f =',res.fun)\r\n    print(res.success)\r\n    return res.x,res.fun,objhist\r\n\r\nif __name__==&quot;__main__&quot;:\r\n    params=&#x5B;100.0,3.0]\r\n    stressmax=&#x5B;1.0,5.0]\r\n    \r\n    xsta,fstar,objhist=runoptimization(params,stressmax)\r\n    import matplotlib.pyplot as plt\r\n    plt.figure()\r\n    plt.semilogy(objhist)\r\n    plt.xlabel('iter', fontsize=17)\r\n    plt.ylabel('obj', fontsize=17)\r\n    plt.savefig(&quot;ex150.png&quot;, dpi=100)\r\n    plt.show()\r\n<\/pre>\n<p>structure.py:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport numpy as np\r\nimport time\r\n\r\ndef structure(x,params):\r\n    mass = (1-x&#x5B;0])**2 + 100*(x&#x5B;1]-x&#x5B;0]**2)**2\r\n    stress = np.zeros(2)\r\n    stress&#x5B;0]=x&#x5B;0]**2 + x&#x5B;1]**2\r\n    stress&#x5B;1]=x&#x5B;0] + params&#x5B;1]*x&#x5B;1]\r\n    return mass,stress\r\n<\/pre>\n<p>Output:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nOptimization terminated successfully    (Exit mode 0)\r\n            Current function value: 0.04567573217474147\r\n            Iterations: 24\r\n            Function evaluations: 75\r\n            Gradient evaluations: 24\r\nx = &#x5B;0.78644243 0.61766166]\r\nf = 0.04567573217474147\r\nTrue\r\n<\/pre>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/01\/ex150-300x200.png?resize=300%2C200\" alt=\"\" width=\"300\" height=\"200\" class=\"alignnone size-medium wp-image-848\" srcset=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/01\/ex150.png?resize=300%2C200&amp;ssl=1 300w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/01\/ex150.png?w=600&amp;ssl=1 600w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>#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&#8217;D:\\projects\\wordpress\\ex150&#8242;) os.getcwd() def runoptimization(params,stressmax): objhist=&#x5B;] def objcon(x): mass,stress=structure(x,params) f=mass g=stressmax-stress objhist.append(mass) return f,g xlast=&#x5B;] flast=&#x5B;] glast=&#x5B;] def obj(x): nonlocal xlast,flast,glast if not np.array_equal(x,xlast): flast,glast = objcon(x) xlast = x return flast def [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","_lmt_disableupdate":"yes","_lmt_disable":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[9,2],"tags":[],"class_list":["post-847","post","type-post","status-publish","format-standard","hentry","category-optimization","category-python"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-dF","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":845,"url":"https:\/\/gantovnik.com\/bio-tips\/2021\/01\/149-optimization-in-python\/","url_meta":{"origin":847,"position":0},"title":"#149 Optimization in python","author":"gantovnik","date":"2021-01-24","format":false,"excerpt":"#149 Optimization in python [code language=\"python\"] import os import numpy as np from scipy.optimize import minimize os.chdir(r'D:\\projects\\wordpress\\ex149') os.getcwd() def obj(x): return (1-x[0])**2 + 100*(x[1]-x[0]**2)**2 def con(x): g=np.zeros(2) g[0]=1-x[0]**2-x[1]**2 g[1]=5-x[0]-3*x[1] return g x0=[5.0,5.0] constraints = {'type': 'ineq','fun': con} options={'disp':True} res = minimize(obj,x0,constraints=constraints,options=options) print('x =',res.x) print('f =',res.fun) print(res.success) [\/code] Output: [code language=\"python\"]\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":495,"url":"https:\/\/gantovnik.com\/bio-tips\/2020\/05\/optimization-with-constraints\/","url_meta":{"origin":847,"position":1},"title":"#72 Optimization with constraints using scipy in python","author":"gantovnik","date":"2020-05-03","format":false,"excerpt":"[code language=\"python\"] 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)2 + (y - 1)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\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"ex72","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2020\/05\/ex72.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2020\/05\/ex72.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2020\/05\/ex72.png?resize=525%2C300 1.5x"},"classes":[]},{"id":1874,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/06\/353-particle-swarm-optimization-using-python\/","url_meta":{"origin":847,"position":2},"title":"#353 Particle swarm optimization using python","author":"gantovnik","date":"2023-06-28","format":false,"excerpt":"[code language=\"python\"] # pip install pyswarms from pyswarms.single.global_best import GlobalBestPSO import numpy as np # Define characteristics of variables: x_min = [0, 0] x_max = [1, 1] bounds = (x_min, x_max) dim = len(x_min) # Define settings of the algorithm: pop = 100 iterations = 250 options = {'c1': 0.5,\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":117,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/optimization-with-contraints\/","url_meta":{"origin":847,"position":3},"title":"#22: Optimization with constraints using SciPy in python","author":"gantovnik","date":"2019-01-03","format":false,"excerpt":"[code language=\"python\"] 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)2 + (X[1]-1)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',\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example22.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example22.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example22.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":1758,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/335-solution-of-nonlinear-equation-using-brent-method-in-python\/","url_meta":{"origin":847,"position":4},"title":"#335 Solution of nonlinear equation by Brent&#8217;s method in python","author":"gantovnik","date":"2023-01-06","format":false,"excerpt":"Brent's method is a hybrid root-finding algorithm combining the bisection method, the secant method, and inverse quadratic interpolation. ex335.py [code language=\"python\"] import numpy as np import matplotlib.pyplot as plt import scipy.optimize as optimize def f(x): return 2*x - 1 + 2*np.cos(np.pi*x) x = np.linspace(0.0,2.0,201) y=f(x) plt.plot(x,y,label='$2x - 1 + 2\\\\cos(\\\\pi\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex335.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1738,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/204-mandelbrot-fractal-using-python-2-2-2-2-2-2-2-2\/","url_meta":{"origin":847,"position":5},"title":"#329 Golden section method using python","author":"gantovnik","date":"2023-01-03","format":false,"excerpt":"golden.py [code language=\"python\"] import math as mt def golden(f,a,b,tol=1.0e-10): # Golden section method for determining x # that minimizes the scalar function f(x). # The minimum must be bracketed in (a,b). c1 = (mt.sqrt(5.0)-1.0)\/2.0 c2 = 1.0 - c1 nIt = int(mt.ceil(mt.log(tol\/abs(a-b))\/mt.log(c1))) # first step x1 = c1*a + c2*b\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex329.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/847","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/comments?post=847"}],"version-history":[{"count":0,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/847\/revisions"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=847"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=847"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=847"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}