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.
JavaScript
x
26
26
1
def func_nlc1(x, a1, a2):
2
.
3
.
4
return val
5
6
def func_nlc1(x, a1, a2):
7
.
8
.
9
return val
10
11
def fitness_function(x, args):
12
.
13
.
14
return val
15
16
17
18
if __name__ == '__main__':
19
20
nlc1 = NonlinearConstraint(func_nlc1, -0.01, 0.01))
21
nlc2 = NonlinearConstraint(func_nlc1, -0.01, 0.01))
22
23
bounds = Bounds([0.0, 0.0], [1.0, 1.0])
24
25
result = differential_evolution(self.fitness_function, args=(a1,a2), bounds=bounds, strategy='rand1bin', constraints=(nlc1, nlc2))
26
Advertisement
Answer
You can use lambda functions:
JavaScript
1
4
1
a1, a2 = 1, 2 # example values
2
nlc1 = NonlinearConstraint(lambda x: func_nlc1(x, a1, a2), -0.01, 0.01))
3
nlc2 = NonlinearConstraint(lambda x: func_nlc1(x, a1, a2), -0.01, 0.01))
4