turning_angle_generator.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import numpy as np
  2. from scipy.interpolate import CubicSpline
  3. import matplotlib.pyplot as plt
  4. def generate_spline_points(points, increment):
  5. """
  6. 使用三次样条曲线拟合并生成根据给定增量生成的拟合点。
  7. :param points: 输入点列表,格式 [(x1, y1), (x2, y2), ...]
  8. :param increment: x 轴增量
  9. :return: 拟合点列表 [(x, y), ...]
  10. """
  11. # 提取 x 和 y
  12. x_points, y_points = zip(*points)
  13. # 构建三次样条
  14. spline = CubicSpline(x_points, y_points)
  15. # 生成根据增量计算的 x 坐标
  16. x_new = np.arange(min(x_points), max(x_points) + increment, increment)
  17. # 计算 y 坐标
  18. y_new = spline(x_new)
  19. # 返回拟合点
  20. return list(zip(x_new, y_new))
  21. if __name__ == "__main__":
  22. # 输入点
  23. # 轨迹 1
  24. # input_points = [(0, 14*3.141592/180), (1, 17*3.141592/180), (2, 2*3.141592/180), (2.5, 0*3.141592/180), (3, 0*3.141592/180)]
  25. # 轨迹 2
  26. input_points = [(0, 16*3.141592/180), (1, 5*3.141592/180), (2, -5*3.141592/180), (3, -16*3.141592/180)]
  27. # 轨迹 3
  28. # input_points = [(0, 0), (1, 0), (2, 0), (3, 0)]
  29. # 轨迹 4
  30. # input_points = [(0, -16*3.141592/180), (1, -5*3.141592/180), (2, 5*3.141592/180), (3, 16*3.141592/180)]
  31. # 轨迹 5
  32. # input_points = [(0, -14*3.141592/180), (1, -17*3.141592/180), (2, -2*3.141592/180), (2.5, 0*3.141592/180), (3, 0*3.141592/180)]
  33. increment = 0.1 # 指定 x 轴增量 (将 M 设置为 50,即在 0 到 3 之间,0.06 的增量将产生 51 个点)
  34. # 生成拟合点
  35. fitted_points = generate_spline_points(input_points, increment)
  36. # 分离 x 和 y 坐标
  37. x_values = [f"{x:.3f}" for x, y in fitted_points]
  38. y_values = [f"{y:.3f}" for x, y in fitted_points]
  39. # 打印为 C++ 代码格式
  40. x_str = "{" + ", ".join(x_values) + "}"
  41. y_str = "{" + ", ".join(y_values) + "}"
  42. # 打印为 C++ 代码格式
  43. x_str = "{" + ", ".join(x_values) + "}"
  44. y_str = "{" + ", ".join(y_values) + "}"
  45. # 将 C++ 代码输出到文件
  46. with open("src/my_planner/scripts/turning_angle.txt", "w") as f:
  47. f.write(f"sampling_times.push_back({x_str});\n")
  48. f.write(f"sampling_turns.push_back({y_str});\n")
  49. print("拟合点已保存到 src/my_planner/scripts/turning_angle.txt 文件中。")
  50. # 绘制图像
  51. plt.figure() # 创建一个新的图形
  52. plt.plot([x for x, y in fitted_points], [y for x, y in fitted_points], label='Spline curve', color='b', linewidth=2)
  53. plt.scatter([x for x, y in input_points], [y for x, y in input_points], color='r', label='Input points', zorder=5)
  54. # 设置标题和标签
  55. plt.title("Cubic Spline Fitting")
  56. plt.xlabel("X")
  57. plt.ylabel("Y")
  58. # 自动调整画布大小
  59. plt.tight_layout()
  60. # 显示图例
  61. plt.legend()
  62. # 显示图形
  63. plt.show()