Map.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import math
  2. from copy import deepcopy
  3. from dijkstra.dijkstra_algorithm import Graph
  4. import numpy as np
  5. import scipy.spatial as spt
  6. import message_pb2 as message
  7. import uuid
  8. class Node(object):
  9. def __init__(self, id, x, y):
  10. self.id_ = id
  11. self.x_ = x
  12. self.y_ = y
  13. def distance(self, other):
  14. if not isinstance(other, (Node, StreetNode, SpaceNode)):
  15. print(" node must be Node,street_node,space_node")
  16. return -1
  17. return math.sqrt(math.pow(other.x_ - self.x_, 2) + math.pow(other.y_ - self.y_, 2))
  18. class StreetNode(Node):
  19. def __init__(self, id, x, y):
  20. Node.__init__(self, id, x, y)
  21. class SpaceNode(Node):
  22. def __init__(self, id, x, y, yaw):
  23. Node.__init__(self, id, x, y)
  24. self.yaw_ = yaw
  25. def frontPoint(self, wheelBase):
  26. x = self.x_ + wheelBase / 2.0 * math.cos(self.yaw_)
  27. y = self.y_ + wheelBase / 2.0 * math.sin(self.yaw_)
  28. return [x, y]
  29. def backPoint(self, wheelBase):
  30. x = self.x_ - wheelBase / 2.0 * math.cos(self.yaw_)
  31. y = self.y_ - wheelBase / 2.0 * math.sin(self.yaw_)
  32. return [x, y]
  33. def singleton(cls):
  34. _instance = {}
  35. def inner():
  36. if cls not in _instance:
  37. _instance[cls] = cls()
  38. return _instance[cls]
  39. return inner
  40. '''
  41. map 采用单例
  42. '''
  43. class DijikstraMap(object):
  44. def __init__(self):
  45. self.nodes_ = {} #dict ,{id: StreetNode/SpaceNode}
  46. self.graph_ = Graph()
  47. def GetVertex(self, id):
  48. return self.nodes_.get(id)
  49. def AddVertex(self, node):
  50. if isinstance(node, (StreetNode)):
  51. print("add street node :%s " % (node.id_))
  52. self.nodes_[node.id_] = node
  53. if isinstance(node, (SpaceNode)):
  54. print("add space node :%s " % (node.id_))
  55. self.nodes_[node.id_] = node
  56. self.graph_.AddVertex(node.id_, [node.x_, node.y_])
  57. return True
  58. def ResetVertexValue(self, node):
  59. self.graph_.ResetVertexValue(node.id_, [node.x_, node.y_])
  60. self.nodes_[node.id_].x_ = node.x_
  61. self.nodes_[node.id_].y_ = node.y_
  62. def AddEdge(self, id1, id2, direct=False):
  63. if self.nodes_.get(id1) == None or self.nodes_.get(id2) == None:
  64. print("Exceptin: Add edge failed")
  65. print(id1, id2)
  66. raise ("Add edge failed %s or %s node is not exist" % (id1, id2))
  67. print("Add Edge :%s-%s" % (id1, id2))
  68. self.graph_.AddEdge(id1, id2)
  69. if direct == False:
  70. self.graph_.AddEdge(id2, id1)
  71. def VertexDict(self):
  72. return self.nodes_
  73. def Edges(self):
  74. return self.graph_.graph_edges
  75. def findNeastNode(self, pt):
  76. labels = []
  77. pts = []
  78. for item in self.nodes_.items():
  79. [label, node] = item
  80. labels.append(label)
  81. pts.append([node.x_, node.y_])
  82. points = np.array(pts)
  83. ckt = spt.KDTree(data=points, leafsize=10)
  84. find_pt = np.array(pt)
  85. d, i = ckt.query(find_pt)
  86. if i >= 0 and i < len(pts):
  87. return [labels[i], pts[i]]
  88. def GetShortestPath(self, beg, end):
  89. [pathId, distance] = self.graph_.shortest_path(beg, end)
  90. print("distance:", distance)
  91. print("path:", pathId)
  92. path = []
  93. for nodeId in pathId:
  94. node = self.nodes_[nodeId]
  95. path.append(node)
  96. return path
  97. @staticmethod
  98. def CreatePath(pathNodes, delta):
  99. last_node = None
  100. trajectry = []
  101. for node in pathNodes:
  102. if last_node == None:
  103. last_node = node
  104. continue
  105. dis = last_node.distance(node)
  106. if dis < 0.5:
  107. last_node = node
  108. continue # 同一点
  109. else:
  110. vector = [node.x_ - last_node.x_, node.y_ - last_node.y_]
  111. dx = vector[0]
  112. dy = vector[1]
  113. yaw = math.asin(dy / math.sqrt(dx * dx + dy * dy))
  114. if yaw >= 0:
  115. if dx < 0:
  116. yaw = math.pi - yaw
  117. if yaw < 0:
  118. if dx < 0:
  119. yaw = -math.pi - yaw
  120. len = int(math.sqrt(dx * dx + dy * dy) / delta)
  121. ax = math.cos(yaw) * delta
  122. ay = math.sin(yaw) * delta
  123. poses = []
  124. if isinstance(last_node, (SpaceNode)):
  125. yaw = yaw + math.pi
  126. for i in range(len + 1):
  127. pose = [last_node.x_ + i * ax, last_node.y_ + i * ay, yaw]
  128. poses.append(pose)
  129. trajectry.append(poses)
  130. last_node = node
  131. return trajectry
  132. @staticmethod
  133. def CreateNavCmd(pose, path):
  134. if len(path) <= 1:
  135. return None
  136. cmd = message.NavCmd()
  137. cmd.action = 0 # 新导航
  138. key = str(uuid.uuid4())
  139. cmd.key = (key)
  140. adjustdiff = message.Pose2d()
  141. node_mpcdiff = message.Pose2d()
  142. enddiff = message.Pose2d()
  143. lastAdjustDiff = message.Pose2d()
  144. # 目标点精度设置
  145. # 原地调整精度
  146. adjustdiff.x = (0.1)
  147. adjustdiff.y = (0.1)
  148. adjustdiff.theta = (0.5 * math.pi / 180.0)
  149. # 过程点巡线目标精度
  150. node_mpcdiff.x = (0.05)
  151. node_mpcdiff.y = (0.05)
  152. node_mpcdiff.theta = (10 * math.pi / 180.0)
  153. # 最后一个巡线目标点精度
  154. enddiff.x = (0.02)
  155. enddiff.y = (0.02)
  156. enddiff.theta = (0.5 * math.pi / 180.0)
  157. # 最后一个原地调整精度
  158. lastAdjustDiff.x = (0.03)
  159. lastAdjustDiff.y = (0.01)
  160. lastAdjustDiff.theta = (0.7 * math.pi / 180.0)
  161. # 速度限制
  162. v_limit = message.SpeedLimit()
  163. angular_limit = message.SpeedLimit()
  164. horize_limit = message.SpeedLimit()
  165. v_limit.min = (0.1)
  166. v_limit.max = (0.2)
  167. horize_limit.min = (0.05)
  168. horize_limit.max = (0.2)
  169. angular_limit.min = (2)
  170. angular_limit.max = (40.0)
  171. # mpc速度限制
  172. mpc_x_limit = message.SpeedLimit()
  173. last_MPC_v = message.SpeedLimit()
  174. mpc_angular_limit = message.SpeedLimit()
  175. mpc_x_limit.min = (0.05)
  176. mpc_x_limit.max = (1.2)
  177. last_MPC_v.min = 0.03
  178. last_MPC_v.max = 0.4
  179. mpc_angular_limit.min = (0 * math.pi / 180.0)
  180. mpc_angular_limit.max = (3 * math.pi / 180.0)
  181. # 创建动作集----------------------
  182. last_node = None
  183. count = 0
  184. for node in path:
  185. if last_node == None:
  186. last_node = node
  187. count += 1
  188. continue
  189. # 运动到上一点
  190. vector = [node.x_ - last_node.x_, node.y_ - last_node.y_]
  191. dx = vector[0]
  192. dy = vector[1]
  193. yaw = math.asin(dy / math.sqrt(dx * dx + dy * dy))
  194. if yaw >= 0:
  195. if dx < 0:
  196. yaw = math.pi - yaw
  197. if yaw < 0:
  198. if dx < 0:
  199. yaw = -math.pi - yaw
  200. if isinstance(last_node, (SpaceNode)):
  201. yaw = yaw + math.pi
  202. # 添加调整动作
  203. act_adjust = message.Action()
  204. act_adjust.type = (1)
  205. act_adjust.target.x = (last_node.x_)
  206. act_adjust.target.y = (last_node.y_)
  207. act_adjust.target.theta = (yaw)
  208. # 最后一个调整点
  209. if count == len(path) - 2:
  210. act_adjust.target_diff.CopyFrom(lastAdjustDiff)
  211. else:
  212. act_adjust.target_diff.CopyFrom(adjustdiff)
  213. act_adjust.velocity_limit.CopyFrom(v_limit)
  214. act_adjust.horize_limit.CopyFrom(horize_limit)
  215. act_adjust.angular_limit.CopyFrom(angular_limit)
  216. cmd.actions.add().CopyFrom(act_adjust)
  217. # 添加mpc动作
  218. act_along = message.Action()
  219. act_along.type = (2)
  220. act_along.begin.x = (last_node.x_)
  221. act_along.begin.y = (last_node.y_)
  222. act_along.begin.theta = (yaw)
  223. act_along.target.x = (node.x_)
  224. act_along.target.y = (node.y_)
  225. act_along.target.theta = (yaw)
  226. if count == len(path) - 1:
  227. act_along.target_diff.CopyFrom(enddiff)
  228. else:
  229. act_along.target_diff.CopyFrom(node_mpcdiff)
  230. if isinstance(node, (SpaceNode)) or isinstance(last_node, (SpaceNode)):
  231. act_along.velocity_limit.CopyFrom(last_MPC_v)
  232. else:
  233. act_along.velocity_limit.CopyFrom(mpc_x_limit)
  234. act_along.angular_limit.CopyFrom(mpc_angular_limit)
  235. cmd.actions.add().CopyFrom(act_along)
  236. last_node = node
  237. count += 1
  238. return cmd
  239. @singleton
  240. class MapManager(object):
  241. def __init__(self):
  242. self.maps={}
  243. self.maps["Base"]=DijikstraMap()
  244. self.maps["Main"]=DijikstraMap()
  245. self.maps["Front"]=DijikstraMap()
  246. self.maps["Back"]=DijikstraMap()
  247. def GetVertex(self, mapName,id):
  248. return self.maps[mapName].GetVertex(id)
  249. def AddVertex(self,mapName, node):
  250. self.maps[mapName].AddVertex(node)
  251. def AddEdge(self,mapName, id1, id2, direct=False):
  252. self.maps[mapName].AddEdge(id1, id2, direct)
  253. def AddVertex_t(self, node):
  254. self.map_t.AddVertex(node)
  255. def Reset(self,mapName):
  256. self.maps[mapName] = DijikstraMap()
  257. def VertexDict(self,mapName):
  258. return self.maps[mapName].VertexDict()
  259. def Edges(self,mapName):
  260. return self.maps[mapName].Edges()
  261. def findNeastNode(self, mapName,pt):
  262. return self.maps[mapName].findNeastNode(pt)
  263. def GetShortestPath(self,mapName, beg, end):
  264. print("beg: ", self.maps[mapName].graph_.points[beg])
  265. print("end: ", self.maps[mapName].graph_.points[end])
  266. return self.maps[mapName].GetShortestPath(beg, end)