{"id":1874,"date":"2023-06-28T00:57:52","date_gmt":"2023-06-28T07:57:52","guid":{"rendered":"https:\/\/gantovnik.com\/bio-tips\/?p=1874"},"modified":"2023-06-28T00:57:52","modified_gmt":"2023-06-28T07:57:52","slug":"353-particle-swarm-optimization-using-python","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2023\/06\/353-particle-swarm-optimization-using-python\/","title":{"rendered":"#353 Particle swarm optimization using python"},"content":{"rendered":"<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# pip install pyswarms\r\nfrom pyswarms.single.global_best import GlobalBestPSO\r\nimport numpy as np\r\n# Define characteristics of variables:\r\nx_min = &#x5B;0, 0]\r\nx_max = &#x5B;1, 1]\r\nbounds = (x_min, x_max)\r\ndim = len(x_min)\r\n# Define settings of the algorithm:\r\npop = 100\r\niterations = 250\r\noptions = {'c1': 0.5, 'c2': 0.4, 'w': 0.9}\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;np.zeros(pop), g1, g2]))\r\n    return -(2 * x + 5 * y) + 150 * penalty ** 2\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    if g1 &gt; 10e-6 or g2 &gt; 10e-6:\r\n        print ('infeasible')\r\n    else:\r\n        print ('feasible')\r\n    print ('x:', x)\r\n    print ('y:', y)\r\n    print ('obj:', 2 * x + 5 * y)\r\n# Model and solve the problem:\r\noptimizer = GlobalBestPSO(n_particles=pop, dimensions=dim,options=options, bounds=bounds)\r\n(obj, variables) = optimizer.optimize(MyOptProb, iterations)\r\n# Display results:\r\nResults(obj, variables)\r\n# Results:\r\n# 2023-06-28 00:54:33,837 - pyswarms.single.global_best - INFO - Optimize for 250 iters with {'c1': 0.5, 'c2': 0.4, 'w': 0.9}\r\n# pyswarms.single.global_best: 100%||250\/250, best_cost=-1.41\r\n# 2023-06-28 00:54:33,995 - pyswarms.single.global_best - INFO - Optimization finished | best cost: -1.4144860266496924, best pos: &#x5B;0.52082104 0.99006058]\r\n# feasible\r\n# x: 1\r\n# y: 0.6718591376856157\r\n# obj: 5.3592956884280785\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p># pip install pyswarms from pyswarms.single.global_best import GlobalBestPSO import numpy as np # Define characteristics of variables: x_min = &#x5B;0, 0] x_max = &#x5B;1, 1] bounds = (x_min, x_max) dim = len(x_min) # Define settings of the algorithm: pop = 100 iterations = 250 options = {&#8216;c1&#8217;: 0.5, &#8216;c2&#8217;: 0.4, &#8216;w&#8217;: 0.9} # Define your [&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,88,2],"tags":[],"class_list":["post-1874","post","type-post","status-publish","format-standard","hentry","category-optimization","category-pso","category-python"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-ue","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":1872,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/06\/352-optimization-using-genetic-algorithm-in-python\/","url_meta":{"origin":1874,"position":0},"title":"#352 Optimization using Genetic Algorithm in python","author":"gantovnik","date":"2023-06-28","format":false,"excerpt":"[code language=\"python\"] #pip install geneticalgorithm import numpy as np from geneticalgorithm import geneticalgorithm as ga # Define charateristics of variables: varbound=np.array([[0,1],[0,1]]) vartype=np.array([['real'],['real']]) # Define settings of the algorithm: algorithm_param = {'max_num_iteration': 100,\\ 'population_size':60,\\ 'mutation_probability':0.1,\\ 'elit_ratio': 0.01,\\ 'crossover_probability': 0.5,\\ 'parents_portion': 0.3,\\ 'crossover_type':'uniform',\\ 'max_iteration_without_improv':None} # Define your optimization model: def MyOptProb(X): y\u2026","rel":"","context":"In &quot;genetic algorithm&quot;","block_context":{"text":"genetic algorithm","link":"https:\/\/gantovnik.com\/bio-tips\/category\/genetic-algorithm\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/06\/ga_history.png?resize=350%2C200&ssl=1","width":350,"height":200},"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":1874,"position":1},"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":1090,"url":"https:\/\/gantovnik.com\/bio-tips\/2021\/11\/189-mandelbrot-set-using-python\/","url_meta":{"origin":1874,"position":2},"title":"#189 Mandelbrot set using python","author":"gantovnik","date":"2021-11-13","format":false,"excerpt":"[code language=\"python\"] import numpy as np import matplotlib.pyplot as plt # This determines the number of colors used in the plot. # The larger the value, the longer the script will take. max_iterations = 50 # These parameters define the boundaries of the plot x_min, x_max = -2.5, 1.5 y_min,\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex189.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex189.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex189.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex189.png?resize=700%2C400&ssl=1 2x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex189.png?resize=1050%2C600&ssl=1 3x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex189.png?resize=1400%2C800&ssl=1 4x"},"classes":[]},{"id":2800,"url":"https:\/\/gantovnik.com\/bio-tips\/2024\/07\/437-particle-swarm-optimization-using-python\/","url_meta":{"origin":1874,"position":3},"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":190,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/coupled-damped-springs-jacobian-is-available\/","url_meta":{"origin":1874,"position":4},"title":"Coupled damped springs (Jacobian is available)","author":"gantovnik","date":"2019-01-10","format":false,"excerpt":"\u00a0 import os import numpy as np import matplotlib.pyplot as plt from scipy import integrate os.chdir(r'D:\\projects\\wordpress\\ex38') os.getcwd() def f(t, y, args): m1, k1, g1, m2, k2, g2 = args return [y[1], - k1\/m1 * y[0] + k2\/m1 * (y[2] - y[0]) - g1\/m1 * y[1], y[3], - k2\/m2 * (y[2]\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example38","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example38.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example38.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example38.png?resize=525%2C300 1.5x"},"classes":[]},{"id":187,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/coupled-damped-springs\/","url_meta":{"origin":1874,"position":5},"title":"Coupled damped springs","author":"gantovnik","date":"2019-01-09","format":false,"excerpt":"\u00a0 import os import numpy as np import matplotlib.pyplot as plt from scipy import integrate os.chdir(r'D:\\projects\\wordpress\\ex37') os.getcwd() def f(t, y, args): m1, k1, g1, m2, k2, g2 = args return [y[1], - k1\/m1 * y[0] + k2\/m1 * (y[2] - y[0]) - g1\/m1 * y[1], y[3], - k2\/m2 * (y[2]\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example37","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example37.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example37.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example37.png?resize=525%2C300 1.5x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/1874","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=1874"}],"version-history":[{"count":0,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/1874\/revisions"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=1874"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=1874"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=1874"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}