python fmin_slsqp - 带约束的错误

时间:2016-09-18 16:41:47

标签: python dynamic scipy economics

我正在练习SciPy,尝试使用fmin_slsqp时遇到错误。我设置了一个问题,我希望在给定一组约束的情况下最大化目标函数U.

我有两个控制变量,x [0,t]和x [1,t],如你所见,它们被t(时间段)索引。目标函数是:

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

约束是在这两个变量上定义的,其中一个变量将变量从一个句点(t)链接到另一个句点(t-1)。

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]
    ])

最后,这里是使用fmin_slsqp:

sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))

不考虑有更好的方法来解决这些动态问题,我的问题是关于语法。运行这个简单的代码时,我收到以下错误:

    Traceback (most recent call last):
  File "xxx", line 34, in <module>
    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 <listcomp>
    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]

我做错了什么?

为参数赋值的代码的初始部分是:

   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) 

1 个答案:

答案 0 :(得分:0)

传递给你的目标和约束函数的数组x将是一个一维数组(就像你的x_init一样)。您不能使用两个索引索引一维数组,因此x[1,0]x[0,t]等表达式将生成错误。