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)?
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 [besidestest
] of theConstraint
is therepair
method. This method tries to fix the given individual. Without defining this method, only a new, random phenotype is created.