Skip to content
Advertisement

How to pass arguments to non-linear constraints in scipy.optimize?

I am trying to use scipy optimization to solve an optimization problem. I have defined the non-linear constraints and fitness functions as shown below in the code. I am able to pass arguments to the fitness function but not to the non-linear constraints. Is there clean way to do it? The arguments to be passed to fitness function and the non-linear constraints are the same.

def func_nlc1(x, a1, a2):
    .
    .
   return val

def func_nlc1(x, a1, a2):
    .
    .
   return val

def fitness_function(x, args):
    .
    .
   return val



if __name__ == '__main__':

   nlc1 = NonlinearConstraint(func_nlc1, -0.01, 0.01))
   nlc2 = NonlinearConstraint(func_nlc1, -0.01, 0.01))

   bounds = Bounds([0.0, 0.0], [1.0, 1.0])

   result = differential_evolution(self.fitness_function, args=(a1,a2), bounds=bounds, strategy='rand1bin', constraints=(nlc1, nlc2))

Advertisement

Answer

You can use lambda functions:

a1, a2 = 1, 2 # example values
nlc1 = NonlinearConstraint(lambda x: func_nlc1(x, a1, a2), -0.01, 0.01))
nlc2 = NonlinearConstraint(lambda x: func_nlc1(x, a1, a2), -0.01, 0.01))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement