Skip to content

Commit 84a145a

Browse files
committed
added two trajectory-related tools into utils
1 parent 2bf28c2 commit 84a145a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/py_utils/utils.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import numpy as np
66
import requests
7+
import scipy.spatial.transform
78

89

910
def is_connect_to_network(url="https://www.google.com", timeout=5):
@@ -222,6 +223,44 @@ def R_to_euler(R):
222223
return np.stack([x, y, z], axis=-1)
223224

224225

226+
def R_to_Q(R):
227+
228+
_valid_shape_rotation_matrix(R)
229+
# scipy's Rotation class uses (x, y, z, w) format for quaternions
230+
return scipy.spatial.transform.Rotation.from_matrix(R).as_quat()
231+
232+
233+
def sample_from_trajectory(
234+
xyz,
235+
qxyzw,
236+
delta_pos=1.5, # meter
237+
delta_angle=np.deg2rad(2), # radian
238+
):
239+
240+
assert len(xyz) == len(qxyzw)
241+
242+
R = Q_to_R(qxyzw)
243+
244+
sampled_idx = [0]
245+
last_pos = xyz[0]
246+
last_R = R[0]
247+
248+
for i in range(1, len(xyz)):
249+
d_pos = np.linalg.norm(xyz[i] - last_pos)
250+
dR = last_R.T @ R[i]
251+
d_angle = np.arccos(R_to_Q(dR)[-1]) * 2
252+
253+
if d_pos >= delta_pos or d_angle >= delta_angle:
254+
sampled_idx.append(i)
255+
last_pos = xyz[i]
256+
last_R = R[i]
257+
258+
if sampled_idx[-1] != len(xyz) - 1:
259+
sampled_idx.append(len(xyz) - 1)
260+
261+
return np.array(sampled_idx)
262+
263+
225264
def _valid_shape_rotation_matrix(R):
226265

227266
if R.ndim < 2 or np.shape(R)[-2:] != (3, 3):

0 commit comments

Comments
 (0)