1

我现在正在努力处理一些代码。我正在尝试对 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()

任何想法/提示?非常感谢提前

4

1 回答 1

0

如果问题出在这条线上:

return cvx.norm([x2-x1,y2-y1])

您可以按如下方式使用vstack :

return cvx.norm(cvx.vstack(x2-x1,y2-y1))

vstack 创建一个 cvx 可以处理的数组。

于 2018-01-24T15:27:46.377 回答