Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with conditional functions in multi-dimension particles #502

Open
someparsa opened this issue Oct 4, 2022 · 0 comments
Open

Problem with conditional functions in multi-dimension particles #502

someparsa opened this issue Oct 4, 2022 · 0 comments

Comments

@someparsa
Copy link

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant