guofei9987/scikit-opt

PSO seens cannot treat equal constraints

Opened this issue · 3 comments

Hi, it seems the equation in PSO doesn't work effectively, this is the code:

def demo_func(x):
    x1, x2 = x
    return -20 * np.exp(-0.2 * np.sqrt(0.5 * (x1 ** 2 + x2 ** 2))) - np.exp(
        0.5 * (np.cos(2 * np.pi * x1) + np.cos(2 * np.pi * x2))) + 20 + np.e

# I add this equation
constraint_eq = [
    lambda x: 2 - x[0] - x[1], 
]

constraint_ueq = (
    lambda x: (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2
    ,
)

max_iter = 50
pso = PSO(func=demo_func, n_dim=2, pop=40, max_iter=max_iter, lb=[-2, -2], ub=[2, 2],
          constraint_eq=constraint_eq, 
          constraint_ueq=constraint_ueq)
pso.record_mode = True
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

# but it seems not effective
print('the sume of x:', sum(pso.gbest_x))

the output is

best_x is  [ 9.51948501e-01 -3.04008149e-04] best_y is [2.57993123]
the sume of x: 0.9516444926553026

we can see that x[0] + x[1] = 2 doesn't work, is there any problem with my code?

起作用了,这是x1+x2<=2

Yes, I am having the same issue. And the constraint sometimes goes over the limited needed. For instance, I have the following constraint:

y = 300
variables are x1, x2, x3
x3 = y - x1 - x2

When I sum x1, x2 and x3 at each step, this is far from the y which the summation should be equal to. Sometimes it is 340, sometimes 260, etc.

And also the way the variables or particles are assigned is not logical. The top boundary is set, and this never changes for other particles or iterations.

I think the algorithm has problems regarding the boundaries and location of particles.

The same applies to un-equal boundaries.