python fmin_slsqp - error with constraints
<p>I am practicing with SciPy and I encountered an error when trying to use fmin_slsqp. I set up a problem in which I want to maximize an objective function, U, given a set of constraints.</p>

<p>I have two control variables, x[0,t] and x[1,t] and, as you can see, they are indexed by t (time periods). The objective function is:</p>

<pre><code>def obj_fct(x, alpha,beta,Al):
U = 0
x[1,0] = x0
for t in trange:
    U = U - beta**t * ( (Al[t]*L)**(1-alpha) * x[1,t]**alpha - x[0,t])
return U
</code></pre>

<p>The constraints are defined over these two variables and one of them links the variables from one period (t) to another (t-1).</p>

<pre><code>def constr(x,alpha,beta,Al):
return np.array([
    x[0,t],
    x[1,0] - x0,
    x[1,t] - x[0,t] - (1-delta)*x[1,t-1]
    ])
</code></pre>

<p>Finally, here is the use of fmin_slsqp:</p>

<pre><code>sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))
</code></pre>

<p>Leaving aside the fact that there are better ways to solve such dynamic problems, my question is about the syntax. When running this simple code, I get the following error:</p>

<pre><code>    Traceback (most recent call last):
  File "xxx", line 34, in &lt;module&gt;
    sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))
  File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 207, in fmin_slsqp
    constraints=cons, **opts)
  File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 311, in _minimize_slsqp
    meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
  File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 311, in &lt;listcomp&gt;
    meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
  File "xxx", line 30, in constr
    x[0,t],
IndexError: too many indices for array
[Finished in 0.3s with exit code 1]
</code></pre>

<p>What am I doing wrong? </p>

<p>The initial part of the code, assigning values to the parameters, is:</p>

<pre><code>   from scipy.optimize import fmin_slsqp
import numpy as np

T = 30
beta = 0.96
L = 1
x0 = 1
gl = 0.02
alpha = 0.3
delta = 0.05
x_init = np.array([1,0.1])

A_l0 = 1000
Al = np.zeros((T+1,1))
Al[1] = A_l0

trange = np.arange(1,T+1,1, dtype='Int8') # does not include period zero
for t in trange: Al[t] = A_l0*(1 + gl)**(t-1) 
</code></pre>

<p>The array <code>x</code> passed to your objective and constraint functions will be a <em>one-dimensional</em> array (just like your <code>x_init</code> is).  You can't index a one-dimensional array with two indices, so expressions such as <code>x[1,0]</code> and <code>x[0,t]</code> will generate an error.</p>

python dynamic scipy economics