wildart / Evolutionary.jl

Evolutionary & genetic algorithms for Julia
Other
324 stars 59 forks source link

WorstFitnessConstraints and PenaltyConstraints examples #82

Open yonachache opened 3 years ago

yonachache commented 3 years ago

Hi, Could you please provide an example of how to define and add WorstFitnessConstraints and PenaltyConstraints to the optimization?

Thanks!

wildart commented 3 years ago

See here: https://wildart.github.io/Evolutionary.jl/dev/constraints/

johnabs commented 2 years ago

Can I follow up here? I've tried following the tutorial to add a basic constraint to a binary GA to solve a knapsack problem, but the constraints clearly aren't being applied, despite adding them to the optimize function.

Effectively, I have 50 (for now) binary values ( x0=BitVector(zeros(50)) ) that determine the value and weight of the knapsack, such that my objective function is:

f(x)=sum(-v.*x) (negative for minimization)

and my constraint function is

c(x)=sum(w.*x)

I then construct the x bounds as lx=zeros(50) and ux=ones(50), then the constraint bounds lc=[0.0] and uc=[970.0], which is the maximum allowable weight of the knapsack.

I define my constraint for the Evolutionary.optimize function:

constraint=WorstFitnessConstraints(lx,ux,lc,uc,c)

Then I define my genetic algorithm:

gafs = GA(populationSize=100,selection=tournament(7),mutation=flip,crossover=singlepoint)

and finally try to run the optimization:

rfs = Evolutionary.optimize(f, constraint, x0, gafs, Evolutionary.Options(iterations=10000))

However, this has always converged to all ones, effectively ignoring the constraint. I've also tried using this with PenaltyConstraints with low, medium, and obscenely high values for the penalty, but with no luck.

Any help here would be awesome, as I tried to follow the tutorial to the letter with constraints, but with a bitvector instead of floats, and this is where I currently am stuck :/

P.S. I've also seen an issue using the uniform binary crossover; should I post that as a new issue?

wildart commented 2 years ago

and my constraint function is

c(x)=sum(w.*x)

The constraint function has to return array of values, so it should be like this

c(x) = [ sum(w.*x) ]

I added new test to the knapsack problem to show usage of the constraints: https://github.com/wildart/Evolutionary.jl/blob/0fd028058eb9a8c4ea0350cb2b2db6788ab8f00b/test/knapsack.jl#L28-L52