I'm using scipy.optimize.minimize with constraints. The example in the documentation ( at http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.minimize.html ) uses for constraints:
cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
{'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
{'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
I'd like to do something similar but generate the elements of this sequence in a loop, but I'm having trouble.
I've tried treating cons as a tuple, an example of the same form as above:
cons = (,)
for i in range(4):
cons += ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + i})
but I get TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'
.
I also tried using str
and eval
:
cons = (str({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1]}))
for i in range(3):
cons += (str({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + i + 1}))
cons = eval(cons)
but that didn't work either, I get something like
cons = eval(cons)
File "<string>", line 1
{'fun': <function <lambda> at 0x062964F0>, 'type': 'eq'}{'fun': <function <lambda> at 0x062964F0>, 'type': 'eq'}{'fun': <function <lambda> at 0x062964F0>, 'type': 'eq'}{'fun': <function <lambda> at 0x062964F0>, 'type': 'eq'}
^
SyntaxError: invalid syntax