Defining constraints in Jenetics

349 views Asked by At

I have previously worked with the MOEA Framework, which knows the concept of constraints. That is, a solution to a problem might have a good fitness, but is infeasible. For instance, when working with the knapsack problem, a particular combination of items may lead to a high profit, but their weight exceeds the knapsack's capacity. A corresponding fitness function would include lines like:

// Set the fitness (=> profit) of the solution (=> knapsack).
solution.setObjective(0, profit)
// Set the constrain (=> 0.0 if OK, , otherwise the distance to the boundary).
solution.setConstraint(0, (weight <= capacity) ? 0.0 : weight - capacity)

Another example in case of a multi-objective knapsack problem would be the constraint that a knapsack is not allowed to use items which are already used in another knapsack.

Has Jenetics something similar? Or how could I encode constraints as part of the fitness function (or somewhere else)?

3

There are 3 answers

0
beatngu13 On BEST ANSWER

As of Jenetic v5.0.0, both phenotypeValidator and genotypeValidator have been removed, but it is now possible to define a Constraint (see also user guide, section 2.5):

Engine.builder(/* ... */)
        .constraint(Constraint.of(phenotype -> /* test validity */)
        .build();

One can also implement Constraint's repair method to try to repair given individuals.

Please note (see this answer):

It [the Constraint interface] is meant as the last line of defense, when it comes to check the validity of an individual. […] The second important method [besides test] of the Constraint is the repair method. This method tries to fix the given individual. Without defining this method, only a new, random phenotype is created.

0
Franz Wilhelmstötter On

Jenetics doesn't support constraints directly. You can set a phenotypeValidator in the Engine.Builder. This will reject Phenotypes and recreate invalid individuals. Not exactly a constraint, but a kind of. The second possibility is to return the minimum fitness value for all objectives for such values.

1
peer On

Please also consider validating your constraints within the fitness function itself and return a value is the opposite of what you are optimising for. This might slow down the overall performance but allows you to validate the result on a higher level.

E.g. if your maximising for a double value just return the lowest negative double as a result of the fitness function, if the optimised solution does not pass the constraints.