ljvmiranda921 / pyswarms

A research toolkit for particle swarm optimization in Python

Home Page:https://pyswarms.readthedocs.io/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problem with conditional functions in multi-dimension particles

someparsa opened this issue · comments

I believe the package cannot handle a few complex-conditioned functions. This is an example.

The function defined in the tutorial for "Basic Optimization with Arguments" is a simple non-conditional function.

Imagine we change such function to a more complex one which has a few IFs and we request more than one particle (n_particles = 10).

Because the input variables are passed to function as numpy arrays, the package fails to do such comparisons. Because it compares full arrays of numpy, for instance x[10:0]>x[10:1] and it correctly cannot handle these comparisons.

This is the error it reports and it means it is comparing arrays not members of arrays and the output is booleans regarding the whole array not its members.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Is there any way to use this package for more complex functions?

This is a minimum working example code which produces such a function and in case it is important, I am on a windows system with a python 3.10+.

# import modules
import numpy as np

# create a parameterized version of the classic Rosenbrock unconstrained optimzation function
def rosenbrock_with_args(x, a, b, c=0):

    tmp0 = x[:, 0]
    tmp1 = x[:, 1]

    if tmp0 > tmp1:
        f = (a - tmp0) ** 2 + b * (tmp1 - tmp0 ** 2) ** 2 + c
    else:
        f = 0
    return f

from pyswarms.single.global_best import GlobalBestPSO

# instatiate the optimizer
x_max = 10 * np.ones(2)
x_min = -1 * x_max
bounds = (x_min, x_max)
options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
optimizer = GlobalBestPSO(n_particles=10, dimensions=2, options=options, bounds=bounds)

# now run the optimization, pass a=1 and b=100 as a tuple assigned to args

cost, pos = optimizer.optimize(rosenbrock_with_args, 1000, a=1, b=100, c=0)