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>Apparently, your constraint is that each column of <code>A</code> should be (element-wise) greater than or equal to the column to its right. </p>

<p>You can formulate a single, vector-outpur constraint as follows:</p>

<pre><code>def cons_fun(x):
    A = x.reshape(3,3) # change "(3,3)" according to the dimensions of A

    return np.array([A[:,i]-A[:,i+1] for i in range(3-1)]).ravel() # change "3" accordingly

cons = ({'type':'ineq',
         'fun' : cons_fun},)
</code></pre>

<p>From my experience with <code>SLSQP</code>, vector-output constraints result in a faster optimization time than providing multiple scalar-output constraints.</p>

python optimization scipy