人工势场法势场可视化
时间: 2025-01-03 09:30:38 浏览: 3
### 人工势场法势场可视化的实现方法
#### 使用Python进行势场可视化
为了更好地理解并展示人工势场法的工作原理,可以通过编程语言如Python来创建势场的可视化效果。Matplotlib库是一个非常适合用于绘制二维图形的选择。
首先定义吸引场和排斥场函数:
```python
import numpy as np
import matplotlib.pyplot as plt
def attractive_field(x, y, goal_x, goal_y, k_att):
dist = np.sqrt((goal_x - x)**2 + (goal_y - y)**2)
f_x = k_att * (x - goal_x)
f_y = k_att * (y - goal_y)
return f_x, f_y, dist
def repulsive_field(x, y, obstacle_list, k_rep, r_obstacle):
sum_f_x = 0.0
sum_f_y = 0.0
for ox, oy, size in obstacle_list:
dx = x - ox
dy = y - oy
dist = max(np.sqrt(dx**2 + dy**2), 0.1)
if dist <= r_obstacle:
fx = k_rep * ((1.0 / dist - 1.0 / r_obstacle) * (dx / dist ** 2))
fy = k_rep * ((1.0 / dist - 1.0 / r_obstacle) * (dy / dist ** 2))
sum_f_x += fx
sum_f_y += fy
return sum_f_x, sum_f_y
```
接着编写一个函数用来计算总力并将结果绘制成图像:
```python
def plot_potential_field(goal, obstacles, grid_size=0.5, k_att=1.0, k_rep=3.0, r_obstacle=7.0):
min_x, min_y = -10, -10
max_x, max_y = 10, 10
x_coords, y_coords = np.meshgrid(
np.arange(min_x, max_x, grid_size),
np.arange(min_y, max_y, grid_size))
fig, ax = plt.subplots()
u = np.zeros_like(x_coords)
v = np.zeros_like(y_coords)
for i in range(len(u)):
for j in range(len(v)):
att_fx, att_fy, _ = attractive_field(x_coords[i][j], y_coords[i][j], goal[0], goal[1], k_att)
rep_fx, rep_fy = repulsive_field(x_coords[i][j], y_coords[i][j], obstacles, k_rep, r_obstacle)
total_force_x = att_fx + rep_fx
total_force_y = att_fy + rep_fy
u[i][j] = total_force_x
v[i][j] = total_force_y
q = ax.quiver(x_coords, y_coords, u, v, units='xy', scale=1/0.2)
ax.plot([goal[0]], [goal[1]], "xr", markersize=8)
for obs in obstacles:
circle = plt.Circle((obs[0], obs[1]), radius=obs[2]+r_obstacle*0.9, color="black", fill=False)
ax.add_patch(circle)
circle = plt.Circle((obs[0], obs[1]), radius=obs[2], color="red")
ax.add_patch(circle)
ax.set_xlim([min_x, max_x])
ax.set_ylim([min_y, max_y])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Potential Field Visualization')
plot_potential_field((-5,-5),( [(4, 4, 1)])) # Example with one obstacle at position (4,4) and a target point (-5,-5).
plt.show()
```
这段代码展示了如何通过矢量图表示各个位置上的合力方向[^1]。这有助于直观地观察到不同区域内的移动趋势——靠近目标的地方会显示出指向目标的力量;而接近障碍物的位置则会有远离这些障碍的趋势。
阅读全文