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, TransformStamped
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(
41  transform: TransformStamped) -> np.ndarray[np.float64, np.dtype[np.float64]]:
42  translation = transform.transform.translation
43  rotation = transform.transform.rotation
44  matrix = np.eye(4)
45  matrix[0, 3] = translation.x
46  matrix[1, 3] = translation.y
47  matrix[2, 3] = translation.z
48  rotation_matrix = tf_transformations.quaternion_matrix([
49  rotation.x,
50  rotation.y,
51  rotation.z,
52  rotation.w
53  ])
54  matrix[:3, :3] = rotation_matrix[:3, :3]
55  return matrix
56 
57 
58 def matrixToTransform(matrix: np.ndarray[np.float64, np.dtype[np.float64]]) -> Transform:
59  transform = Transform()
60  transform.translation.x = matrix[0, 3]
61  transform.translation.y = matrix[1, 3]
62  transform.translation.z = matrix[2, 3]
63  quaternion = tf_transformations.quaternion_from_matrix(matrix)
64  transform.rotation.x = quaternion[0]
65  transform.rotation.y = quaternion[1]
66  transform.rotation.z = quaternion[2]
67  transform.rotation.w = quaternion[3]
68  return transform
69 
70 
71 def worldToMap(world_x: float, world_y: float, map_msg: OccupancyGrid) -> tuple[int, int]:
72  map_x = int(math.floor((world_x - map_msg.info.origin.position.x) / map_msg.info.resolution))
73  map_y = int(math.floor((world_y - map_msg.info.origin.position.y) / map_msg.info.resolution))
74  return map_x, map_y
75 
76 
77 def getMapOccupancy(x: int, y: int, map_msg: OccupancyGrid): # type: ignore[no-untyped-def]
78  return map_msg.data[y * map_msg.info.width + x]