Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
utils.py
1 # Copyright (c) 2024 Open Navigation LLC
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 
16 import math
17 
18 from geometry_msgs.msg import Quaternion, Transform
19 from nav_msgs.msg import OccupancyGrid
20 import numpy as np
21 import tf_transformations
22 
23 """
24 Transformation utilities for the loopback simulator
25 """
26 
27 
28 def addYawToQuat(quaternion: Quaternion, yaw_to_add: float) -> Quaternion:
29  q = [quaternion.x, quaternion.y, quaternion.z, quaternion.w]
30  q2 = tf_transformations.quaternion_from_euler(0.0, 0.0, yaw_to_add)
31  q_new = tf_transformations.quaternion_multiply(q, q2)
32  new_quaternion = Quaternion()
33  new_quaternion.x = q_new[0]
34  new_quaternion.y = q_new[1]
35  new_quaternion.z = q_new[2]
36  new_quaternion.w = q_new[3]
37  return new_quaternion
38 
39 
40 def transformStampedToMatrix(transform: Transform) -> np.ndarray[np.float64, np.dtype[np.float64]]:
41  translation = transform.transform.translation
42  rotation = transform.transform.rotation
43  matrix = np.eye(4)
44  matrix[0, 3] = translation.x
45  matrix[1, 3] = translation.y
46  matrix[2, 3] = translation.z
47  rotation_matrix = tf_transformations.quaternion_matrix([
48  rotation.x,
49  rotation.y,
50  rotation.z,
51  rotation.w
52  ])
53  matrix[:3, :3] = rotation_matrix[:3, :3]
54  return matrix
55 
56 
57 def matrixToTransform(matrix: np.ndarray[np.float64, np.dtype[np.float64]]) -> Transform:
58  transform = Transform()
59  transform.translation.x = matrix[0, 3]
60  transform.translation.y = matrix[1, 3]
61  transform.translation.z = matrix[2, 3]
62  quaternion = tf_transformations.quaternion_from_matrix(matrix)
63  transform.rotation.x = quaternion[0]
64  transform.rotation.y = quaternion[1]
65  transform.rotation.z = quaternion[2]
66  transform.rotation.w = quaternion[3]
67  return transform
68 
69 
70 def worldToMap(world_x: float, world_y: float, map_msg: OccupancyGrid) -> tuple[int, int]:
71  map_x = int(math.floor((world_x - map_msg.info.origin.position.x) / map_msg.info.resolution))
72  map_y = int(math.floor((world_y - map_msg.info.origin.position.y) / map_msg.info.resolution))
73  return map_x, map_y
74 
75 
76 def getMapOccupancy(x: int, y: int, map_msg: OccupancyGrid): # type: ignore[no-untyped-def]
77  return map_msg.data[y * map_msg.info.width + x]