scipy.optimize compact constraints
<p>I have a np.array A of length 9 and it is the variable in the objective function. </p>

<pre><code>A =  [ a1, a2, a3,
       b1, b2, b3,
       c1, c2, c3], where a1...c3 are real numbers.
with constraints: a1 &gt; a2, a2 &gt; a3,
                  b1 &gt; b2, b2 &gt; b3,
                  c1 &gt; c2, c2 &gt; c3
</code></pre>

<p>Is there any easy way to write the constraints? currently I have the following code, but as the array size gets larger, it is difficult to write them all.</p>

<pre><code>cons = (
        {'type':'ineq',
         'fun': lambda x : np.array([x[0]-x[1]])
        }
    ,
        {'type':'ineq',
         'fun': lambda x : np.array([x[1]-x[2]])
        }
    ,
        {'type':'ineq',
         'fun': lambda x : np.array([x[3]-x[4]])
        }    
    ,
        {'type':'ineq',
         'fun': lambda x : np.array([x[4]-x[5]])
        }   
    ,
        {'type':'ineq',
         'fun': lambda x : np.array([x[6]-x[7]])
        }    
    ,
        {'type':'ineq',
         'fun': lambda x : np.array([x[7]-x[8]])
        }    
   )
</code></pre>

<p>I would imagine scipy likes a numeric output from each of these functions rather than boolean, so that rules out more than two inputs per function... (degrees of freedom and all that isht) what you can do is write a list comprehension to make the functions for you...</p>

<pre><code>cons = ({'type':'ineq', 'fun': lambda x: x[i] - x[i+1]} for i in range(len(A)-1))
</code></pre>

<p>I'm not sure why you would need to cast the result of subtraction to a 1-length array, so I left it out.. it's easy to put back in</p>

python optimization scipy