Skip to content Skip to sidebar Skip to footer

Providing Constraints In Pymoo Optimisation

I have an objective function which looks like: f1 = -1 * (constant1 * (variable1 - constant2)) And I have a constraint such that the function f1 should only take values between 10

Solution 1:

First, I would like to note that your objective function is a simple linear function which needs to be bounded in the design space to be bounded in the objective space. I assume your example is a proof of concept anyway. As you already stated in your question you have to define two constraints, one limiting f1 < 20 and the other limiting f1 > 10. You do not need any Repair operator to achieve what you want to achieve. Also, having a boundary on an objective makes the repair very difficult in general. However, for your simple problem it would be also quite easy to implement (but would not really make sense generally speaking).

To achieve what you are intending to do you have to formulate the problem to be compliant with the pymoo definition. In pymoo the constraint violation is defined as follows: A solution is considered as feasible of all constraint violations are less than zero. A solution is considered as infeasible if at least one constraint violation is larger than zero. Therefore, the expressions above need to be correct (basically flipped). g1 = 10 - f1 is less than zero (satisfied) when f1 is larger than 10. g2 = f1 - 20 is less than zero (satisfied) when f1 is less than 20. A complete running code example looks as follows:

import numpy as np

from pymoo.algorithms.so_pattern_search import PatternSearch
from pymoo.model.problem import Problem
from pymoo.optimize import minimize


classMyProblem(Problem):

    def__init__(self, const_1, const_2):
        super().__init__(n_var=1, n_obj=1, n_constr=2, xl=0, xu=100, type_var=np.double)
        self.const_1 = const_1
        self.const_2 = const_2

    def_evaluate(self, x, out, *args, **kwargs):
        f = - (self.const_1 * (x[:, 0] - self.const_2))

        g1 = f - 20.0
        g2 = 10.0 - f
        G = np.column_stack([g1, g2])

        out["F"], out["G"] = f, G


problem = MyProblem(100.0, 1.0)

algorithm = PatternSearch()

res = minimize(problem,
               algorithm,
               seed=1,
               verbose=False)

print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))

For this example, make sure you define const_1 and const_2 to be able to obtain an objective value in your defined range. Otherwise, the algorithm will not be able to find a feasible solution.

Moreover, I would like to mention that more details about implementing objective and constraint functions given a mathematical expression are explained in our getting started guide.

Post a Comment for "Providing Constraints In Pymoo Optimisation"