1

I'm trying to write out a dynamic constraint list with the pattern x[i-1] < x[i] with an unknown length of i.

So far, I've tried it non dynamically:

cons = [{'type':'eq', 'fun': lambda x: x[0]-1},
        {'type':'ineq','fun': lambda x: x[0]-x[1]},
        {'type':'ineq','fun': lambda x: x[1]-x[2]},
        {'type':'ineq','fun': lambda x: x[2]-x[3]},]

And that works fine. When I try to loop through dynamically, it works when i is 2 or 3 but fails at >= 4

cons2 =[{'type':'eq', 'fun': lambda x: x[0]-1}]

for j in range(1,periods):
    a = {'type':'ineq', 'fun': lambda x: x[j-1] - x[j]}
    cons2.append(a)

Output when i = 2 (both)

x: array([1.        , 0.32822429])

Output when i = 3 (both)

x: array([1.        , 0.41383429, 0.41383429])

Output when i = 4 (dynamically coded)

x: array([1.        , 0.15914709, 0.56579436, 0.56579436])

Output when i = 4 (hard coded)

x: array([1.        , 0.43127982, 0.43127982, 0.43127982])

Any help pointing out why or where this breaking down (and the fix) would be greatly appreciated!

Thanks,

Rich

  • [late binding closures *gotcha*](https://stackoverflow.com/questions/37791680/scipy-optimize-minimize-slsqp-with-linear-constraints-fails/37792650#37792650); [another example](https://stackoverflow.com/questions/45491376/scipy-optimization-not-running-when-i-try-to-set-constraints-using-a-for-loop/45493887#45493887) – Warren Weckesser Jun 05 '18 at 12:35
  • That makes a lot of sense and the solution listed in "another example" worked. Thanks Warren. – Richard Wolff Jun 05 '18 at 12:45

0 Answers0