Skip to content
Advertisement

Generating constraints for optimization in scipy using loop

There are lots of constraints which I will use in optimization using scipy; so I need to generate the constraints by loop. Below there’s a sample of my constraints:

cons = ({'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 2},
        {'type': 'ineq', 'fun': lambda x: -x[1] - 2 * x[1] + 2},
        {'type': 'ineq', 'fun': lambda x: -x[2] - 2 * x[1] + 2})

There constraints are more than three… I use following loop to generate but I couldn’t get the same output.

cons ={}
for i in range(50):
    cons['type'] = 'ineq'
    cons['fun'] = lambda x: -x[i] - 2 * x[1] + 2

Advertisement

Answer

You are updating cons everytime. Try this

_tmp = []
for i in range(50):
    _tmp.append({'type':'ineq', 'fun': lambda x: -x[i] - 2 * x[1] + 2})

cons = tuple(_tmp)

And this is more pythonic

cons = tuple([{'type':'ineq', 'fun': lambda x: -x[i] - 2 * x[1] + 2} for i in range(50)])
Advertisement