{"id":1872,"date":"2023-06-28T00:51:21","date_gmt":"2023-06-28T07:51:21","guid":{"rendered":"https:\/\/gantovnik.com\/bio-tips\/?p=1872"},"modified":"2023-06-28T00:51:22","modified_gmt":"2023-06-28T07:51:22","slug":"352-optimization-using-genetic-algorithm-in-python","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2023\/06\/352-optimization-using-genetic-algorithm-in-python\/","title":{"rendered":"#352 Optimization using Genetic Algorithm in python"},"content":{"rendered":"<p><a href=\"https:\/\/gantovnik.com\/bio-tips\/2023\/06\/352-optimization-using-genetic-algorithm-in-python\/ga_history\/\" rel=\"attachment wp-att-1873\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/06\/ga_history.png?resize=407%2C278&#038;ssl=1\" alt=\"\" width=\"407\" height=\"278\" class=\"alignnone size-full wp-image-1873\" srcset=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/06\/ga_history.png?w=407&amp;ssl=1 407w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/06\/ga_history.png?resize=300%2C205&amp;ssl=1 300w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/06\/ga_history.png?resize=150%2C102&amp;ssl=1 150w\" sizes=\"(max-width: 407px) 100vw, 407px\" \/><\/a><\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n#pip install geneticalgorithm\r\nimport numpy as np\r\nfrom geneticalgorithm import geneticalgorithm as ga\r\n# Define charateristics of variables:\r\nvarbound=np.array(&#x5B;&#x5B;0,1],&#x5B;0,1]])\r\nvartype=np.array(&#x5B;&#x5B;'real'],&#x5B;'real']])\r\n\r\n# Define settings of the algorithm:\r\nalgorithm_param = {'max_num_iteration': 100,\\\r\n                   'population_size':60,\\\r\n                   'mutation_probability':0.1,\\\r\n                   'elit_ratio': 0.01,\\\r\n                   'crossover_probability': 0.5,\\\r\n                   'parents_portion': 0.3,\\\r\n                   'crossover_type':'uniform',\\\r\n                   'max_iteration_without_improv':None}  \r\n    \r\n# Define your optimization model:\r\ndef MyOptProb(X):\r\n    y = 0+X&#x5B;1]*(1.29-0)\r\n    x = np.round(0+X&#x5B;0]*(2-0))\r\n    g1 = 5\/10 * x + 3\/10 * y - 1\r\n    g2 = 2\/9 * x + 7\/9 * y - 1\r\n    penalty = np.amax(np.array(&#x5B;0,g1,g2]))\r\n    return -(2*x+5*y)+150*penalty**2\r\n\r\n# Define a solution retriever:\r\ndef Results(obj, variables):\r\n    x = round(0+variables&#x5B;0]*(2-0))\r\n    y = 0+variables&#x5B;0]*(1.29-0)\r\n    g1 = 5 * x + 3 * y - 10\r\n    g2 = 2 * x + 7 * y - 9\r\n    print(g1)\r\n    print(g2)\r\n    if g1&gt;10e-6 or g2&gt;10e-6:\r\n      print(&quot;infeasible&quot;)\r\n    else:\r\n      print(&quot;feasible&quot;)\r\n    print(&quot;x:&quot;,x)\r\n    print(&quot;y:&quot;,y)\r\n    print(&quot;obj:&quot;,2*x+5*y)\r\n\r\n# Model and solve the problem:\r\nmodel=ga(function=MyOptProb,dimension=2,\r\n         variable_type_mixed=vartype,variable_boundaries=varbound,\r\n         algorithm_parameters=algorithm_param)\r\nmodel.run()\r\n# Display results:    \r\nResults(model.best_function,model.best_variable) \r\n# The best solution found:                                                                           \r\n# &#x5B;0.41141754 0.79674808]\r\n# Objective function:\r\n# -7.068871696566733\r\n# -3.40781412393091\r\n# -3.284899622505458\r\n# feasible\r\n# x: 1\r\n# y: 0.5307286253563631\r\n# obj: 4.653643126781816\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>#pip install geneticalgorithm import numpy as np from geneticalgorithm import geneticalgorithm as ga # Define charateristics of variables: varbound=np.array(&#x5B;&#x5B;0,1],&#x5B;0,1]]) vartype=np.array(&#x5B;&#x5B;&#8217;real&#8217;],&#x5B;&#8217;real&#8217;]]) # Define settings of the algorithm: algorithm_param = {&#8216;max_num_iteration&#8217;: 100,\\ &#8216;population_size&#8217;:60,\\ &#8216;mutation_probability&#8217;:0.1,\\ &#8216;elit_ratio&#8217;: 0.01,\\ &#8216;crossover_probability&#8217;: 0.5,\\ &#8216;parents_portion&#8217;: 0.3,\\ &#8216;crossover_type&#8217;:&#8217;uniform&#8217;,\\ &#8216;max_iteration_without_improv&#8217;:None} # Define your optimization model: def MyOptProb(X): y = 0+X&#x5B;1]*(1.29-0) x = np.round(0+X&#x5B;0]*(2-0)) g1 = [&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_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":"","jetpack_post_was_ever_published":false},"categories":[86,9,2],"tags":[87,25],"class_list":["post-1872","post","type-post","status-publish","format-standard","hentry","category-genetic-algorithm","category-optimization","category-python","tag-genetic-algorithm","tag-optimization"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-uc","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":1874,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/06\/353-particle-swarm-optimization-using-python\/","url_meta":{"origin":1872,"position":0},"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":2800,"url":"https:\/\/gantovnik.com\/bio-tips\/2024\/07\/437-particle-swarm-optimization-using-python\/","url_meta":{"origin":1872,"position":1},"title":"#437 Particle swarm optimization using python","author":"gantovnik","date":"2024-07-20","format":false,"excerpt":"import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def f(x,y): return (x-3.14)**2 + (y-2.72)**2 + np.sin(3*x+1.41) + np.sin(4*y-1.73) # Compute and plot the function in 3D within [0,5]x[0,5] x, y = np.array(np.meshgrid(np.linspace(0,5,100), np.linspace(0,5,100))) z = f(x, y) # Find the global minimum x_min = x.ravel()[z.argmin()] y_min\u2026","rel":"","context":"In &quot;animation&quot;","block_context":{"text":"animation","link":"https:\/\/gantovnik.com\/bio-tips\/category\/animation\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex437.gif?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex437.gif?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex437.gif?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex437.gif?resize=700%2C400&ssl=1 2x"},"classes":[]},{"id":2634,"url":"https:\/\/gantovnik.com\/bio-tips\/2024\/07\/436-non-convex-univariate-function-optimization-using-brents-method-in-python\/","url_meta":{"origin":1872,"position":2},"title":"#436 Non-convex univariate function optimization using Brent&#8217;s method in python","author":"gantovnik","date":"2024-07-18","format":false,"excerpt":"Brent\u2019s method is an optimization algorithm that combines a bisecting algorithm (Dekker\u2019s method) and inverse quadratic interpolation. It can be used for constrained and unconstrained univariate function optimization. The Brent-Dekker method is an extension of the bisection method. It is a root-finding algorithm that combines elements of the secant method\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\/2024\/07\/ex436.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex436.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex436.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":1872,"position":3},"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":1774,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/338-minimization-using-newtons-method-on-the-non-quadratic-problem-in-python\/","url_meta":{"origin":1872,"position":4},"title":"#338 Minimization using Newton\u2019s method on the non-quadratic problem in python","author":"gantovnik","date":"2023-01-16","format":false,"excerpt":"ex338.py [code language=\"python\"] import numpy as np import math import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') def my_f(x): #$f(x_1, x_2) = e^{x_1+3x_2-0.1}+e^{x_1-3x_2-0.1}+e^{-x_1-0.1}$ x1 = x[0, 0] x2 = x[1, 0] return math.exp(x1+3*x2-0.1)+math.exp(x1-3*x2-0.1)+math.exp(-x1-0.1) def my_gradient_f(x): #$\\nabla f(x_1, x_2)$ x1 = x[0, 0] x2 = x[1, 0] gradient_1=1*math.exp(x1+3*x2-0.1)+1*math.exp(x1-3*x2-0.1)-math.exp(-x1-0.1) gradient_2=3*math.exp(x1+3*x2-0.1)-3*math.exp(x1-3*x2-0.1) return np.array([[gradient_1], [gradient_2]])\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\/ex338.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex338.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex338.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex338.png?resize=700%2C400&ssl=1 2x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex338.png?resize=1050%2C600&ssl=1 3x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex338.png?resize=1400%2C800&ssl=1 4x"},"classes":[]},{"id":104,"url":"https:\/\/gantovnik.com\/bio-tips\/2018\/12\/unconstrained-multivariate-optimization\/","url_meta":{"origin":1872,"position":5},"title":"Unconstrained multivariate optimization","author":"gantovnik","date":"2018-12-31","format":false,"excerpt":"import os import matplotlib.pyplot as plt import numpy as np import scipy import sympy os.chdir('\/home\/vg\/Downloads\/projects\/ex18') os.getcwd() x1,x2=sympy.symbols(\"x_1,x_2\") f_sym=(x1-1)**4 + 5*(x2-1)**2 - 2*x1*x2 fprime_sym=[f_sym.diff(x_) for x_ in (x1,x2)] sympy.Matrix(fprime_sym) fhess_sym=[[f_sym.diff(x1_,x2_) for x1_ in (x1,x2)] for x2_ in (x1,x2)] sympy.Matrix(fhess_sym) f_lmbda=sympy.lambdify((x1,x2),f_sym,'numpy') fprime_lmbda=sympy.lambdify((x1,x2),fprime_sym,'numpy') fhess_lmbda=sympy.lambdify((x1,x2),fhess_sym,'numpy') def func_XY_to_xy(f): return lambda X: np.array(f(X[0],X[1])) f=func_XY_to_xy(f_lmbda) fprime=func_XY_to_xy(fprime_lmbda) fhess=func_XY_to_xy(fhess_lmbda)\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example18","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example18.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example18.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example18.png?resize=525%2C300 1.5x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/1872","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=1872"}],"version-history":[{"count":0,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/1872\/revisions"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=1872"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=1872"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=1872"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}