2

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))
naseefo
  • 720
  • 1
  • 9
  • 30
  • What does "I am not able to pass arguments to the non-linear constraints." mean? Have you read the docs and provided examples? What is the exact issue? [ask] – Julien Jul 20 '21 at 06:36
  • Yes, I read through the scipy.optimize documentation. It doesn't explicitly mention how we can pass arguments to nonlinear constraints. – naseefo Jul 20 '21 at 06:44
  • @joni Thank you for the solution. I checked it out and its working! – naseefo Jul 20 '21 at 16:39

1 Answers1

4

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))
joni
  • 6,840
  • 2
  • 13
  • 20