我现在正在努力解决一些代码问题。我试图对2D轨迹进行凸优化,并且我试图最小化速度差异。问题是计算当前速度(通过在时间步长t-1和t + 1中使用我的解向量x),但是当我尝试使用凸范数方法创建新向量时会出现问题
import cvxpy as cvx
#costFunction, sum integral
def costFunction(x):
outputSum = 0.0
for i in range(1,amountSamplePoints):
outputSum = outputSum + (getJvel(i,x)) * 0.5
return outputSum
#get velocity at time t
def getVel(t,x):
x2=x[2*(t+1)]
y2=x[2*(t+1)+1]
x1=x[2*(t-1)]
y1=x[2*(t-1)+1]
#return cvx.norm(x[2*(t-1):2*t:1])
return cvx.norm([x2-x1,y2-y1])
def getJvel(t,x):
return cvx.square(20.0-getVel(t,x))
# Problem data.
x = cvx.Variable(12)
# Construct the problem.
objective = cvx.Minimize(costFunction(x))
constraints = []
prob = cvx.Problem(objective, constraints)
prob.solve()
我得到了:
>>> (executing file "sampleCode.py")
Traceback (most recent call last):
File "/home/fornubuntu/Documents/Python Projects/sampleCode.py", line 26, in <module>
objective = cvx.Minimize(costFunction(x))
File "/home/fornubuntu/Documents/Python Projects/sampleCode.py", line 7, in costFunction
outputSum = outputSum + (getJvel(i,x)) * 0.5
File "/home/fornubuntu/Documents/Python Projects/sampleCode.py", line 20, in getJvel
return cvx.square(20.0-getVel(t,x))
File "/home/fornubuntu/Documents/Python Projects/sampleCode.py", line 17, in getVel
return cvx.norm([x2-x1,y2-y1])
File "/home/fornubuntu/anaconda3/lib/python3.5/site-packages/cvxpy/atoms/norm.py", line 41, in norm
x = Expression.cast_to_const(x)
File "/home/fornubuntu/anaconda3/lib/python3.5/site-packages/cvxpy/expressions/expression.py", line 238, in cast_to_const
return expr if isinstance(expr, Expression) else cvxtypes.constant()(expr)
File "/home/fornubuntu/anaconda3/lib/python3.5/site-packages/cvxpy/expressions/constants/constant.py", line 42, in __init__
self._value = intf.DEFAULT_INTF.const_to_matrix(value)
File "/home/fornubuntu/anaconda3/lib/python3.5/site-packages/cvxpy/interface/base_matrix_interface.py", line 47, in new_converter
if not convert_scalars and cvxpy.interface.matrix_utilities.is_scalar(value):
File "/home/fornubuntu/anaconda3/lib/python3.5/site-packages/cvxpy/interface/matrix_utilities.py", line 150, in is_scalar
return size(constant) == (1, 1)
File "/home/fornubuntu/anaconda3/lib/python3.5/site-packages/cvxpy/interface/matrix_utilities.py", line 131, in size
return (len(constant[0]), len(constant))
TypeError: object of type 'AddExpression' has no len()
任何想法/提示? 非常感谢提前
答案 0 :(得分:0)
如果问题出在行中:
return cvx.norm([x2-x1,y2-y1])
您可以按如下方式使用vstack:
return cvx.norm(cvx.vstack(x2-x1,y2-y1))
vstack创建一个cvx可以处理的数组。