我只是想使用人工势场(APF)模拟一个简单的路径规划问题。为此,我有一个Point
类,每个类的实例代表代理的位置。实现了一系列功能,用于移动代理的位置,查找其与其他点的距离以及计算与之对应的APF。还定义了一个Obstacle
类,除了障碍物的半径之外,每个类的实例都只是一个点。
import autograd.numpy as np
from autograd import grad
import math
class Point(object):
def __init__(self,x,y):
self.X = x
self.Y = y
def distance(self, goal):
dx = self.X - goal.X
dy = self.Y - goal.Y
return math.hypot(dx, dy)
def move(self, value):
self.X += value
self.Y += value
def APF(self, goal, k, obstacles):
num = self.distance(goal)**2
temp = self.distance(goal)**(2*k)
for item in obstacles:
temp = temp + (self.distance(item.point)**2 - item.radius**2)
den = temp**(1/k)
return num/den
class Obstacle(object):
def __init__(self, point, radius):
self.point = point
self.radius = radius
要测试上面的代码,请考虑以下主要代码段。特别是,应该迭代地计算APF的梯度,并将结果添加到代理的位置(例如,移动它),直到梯度消失为止。
if __name__== "__main__" :
start = Point(0.0, 0.0)
goal = Point(15.0, 5.0)
p1 = Point(2.0, 2.0)
p2 = Point(3.0, 3.0)
p3 = Point(4.0, 4.0)
p4 = Point(5.0, 5.0)
obs1 = Obstacle(p1, 1.0)
obs2 = Obstacle(p2, 2.0)
obs3 = Obstacle(p3, 3.0)
obs4 = Obstacle(p4, 4.0)
obstacles = [obs1, obs2, obs3, obs4]
trajectory = [start]
k = 7.0
temp = start
while grad(temp.APF(goal, k, obstacles)) != 0.0:
next = temp.move(grad(temp.APF(goal, k, obstacles)))
trajctory.append(next)
temp = next
但是,我遇到了以下错误:
Traceback (most recent call last):
File "test_APF.py", line 53, in <module>
next = temp.move(grad(temp.APF(goal, k, obstacles)))
File "test_APF.py", line 17, in move
self.X += value
TypeError: unsupported operand type(s) for +=: 'float' and 'function'
对我来说APF
返回数字,因此grad
应该可以接受。然后,move
还将接收数字作为其参数。您能帮我发现问题吗?
答案 0 :(得分:2)
根据the Autograd readme,autograd.grad()
返回一个函数。
>>> grad_tanh = grad(tanh) # Obtain its gradient function
>>> grad_tanh(1.0) # Evaluate the gradient at x = 1.0
您正在将函数而不是其返回值传递给.move()
函数。
答案 1 :(得分:2)
import autograd.numpy as np
from autograd import grad
import math
def APF(k,start,goal, obstacles):
dist = math.hypot(start[0] - goal[0], start[1] - goal[1])
num = dist**2
temp = dist**(2*k)
for item in obstacles:
temp = temp + (dist ** 2 - item.radius ** 2)
den = temp ** (1 / k)
return num / den
class Point(object):
def __init__(self,x,y):
self.X = x
self.Y = y
def distance(self, goal):
dx = self.X - goal.X
dy = self.Y - goal.Y
return math.hypot(dx, dy)
def move(self, value):
self.X += value
self.Y += value
class Obstacle(object):
def __init__(self, point, radius):
self.point = point
self.radius = radius
if __name__== "__main__" :
start = (0.0, 0.0)
goal = (15.0, 5.0)
p1 = Point(2.0, 2.0)
p2 = Point(3.0, 3.0)
p3 = Point(4.0, 4.0)
p4 = Point(5.0, 5.0)
obs1 = Obstacle(p1, 1.0)
obs2 = Obstacle(p2, 2.0)
obs3 = Obstacle(p3, 3.0)
obs4 = Obstacle(p4, 4.0)
obstacles = [obs1, obs2, obs3, obs4]
trajectory = [start]
k = 7.0
temp = start
print(grad(APF)(k,start,goal, obstacles))
# next = temp.move(grad(temp.APF(goal, k, obstacles)))
# trajctory.append(next)
# temp = next
您必须创建两个类来处理此问题。有关信息,请参见我的参考类。