-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathVclSimuBackend-raw.py
8022 lines (6584 loc) · 340 KB
/
VclSimuBackend-raw.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# cython:language_level=3
from argparse import ArgumentParser, Namespace
import copy
import datetime
from enum import IntEnum
import json
import logging
import numpy as np
import os
import pickle
import platform
import random
from scipy.ndimage import filters
from scipy import signal
from scipy.spatial.transform import Rotation
from scipy.spatial.transform import Rotation as R
from scipy.interpolate import interp1d
import time
import tkinter as tk
from tkinter import filedialog
from typing import Dict, Any, List, Tuple, Union, Iterable, Optional, IO, Set
import ModifyODE as ode
from MotionUtils import (
quat_to_rotvec_fast, quat_to_matrix_fast, quat_to_vec6d_fast,
quat_from_rotvec_fast,
six_dim_mat_to_quat_fast,
quat_inv_single_fast,
quat_apply_forward_one2many_fast,
quat_apply_single_fast,
decompose_rotation_single_fast,
quat_apply_forward_fast,
quat_multiply_forward_fast
)
class Common:
class GetFileNameByUI:
@staticmethod
def get_file_name_by_UI(initialdir="./", filetypes=[("all_file_types", "*.*")]):
root = tk.Tk()
root.withdraw()
return filedialog.askopenfilename(initialdir=initialdir, filetypes = filetypes)
@staticmethod
def get_multi_file_name_by_UI():
root = tk.Tk()
root.withdraw()
return filedialog.askopenfilenames()
class Helper:
_empty_str_list = ["", "null", "none", "nullptr", "no", "not", "false", "abort"]
_true_str_list = ["yes", "true", "confirm", "ok", "sure", "ready"]
def __init__(self):
pass
@staticmethod
def get_curr_time() -> str:
return time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
@staticmethod
def print_total_time(starttime):
endtime = datetime.datetime.now()
delta_time = endtime - starttime
# logging.info(f"start time: {starttime.strftime('%Y-%m-%d %H:%M:%S')}")
# logging.info(f"end time: {endtime.strftime('%Y-%m-%d %H:%M:%S')}")
# logging.info(f"delta time: {delta_time}")
# logging.info(f"seconds = {delta_time.seconds}")
print(f"\n\nstart time: {starttime.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"end time: {endtime.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"delta time: {delta_time}")
print(f"seconds = {delta_time.seconds}", flush=True)
@staticmethod
def is_str_empty(s: str) -> bool:
return s.lower() in Common.Helper._empty_str_list
@staticmethod
def str_is_true(s: str) -> bool:
return s.lower() in Common.Helper._true_str_list
@staticmethod
def conf_loader(fname: str) -> Dict[str, Any]:
with open(fname, "r") as f:
conf: Dict[str, Any] = json.load(f)
filename_conf: Dict[str, str] = conf["filename"]
for k, v in filename_conf.items():
if k.startswith("__"):
continue
filename_conf[k] = os.path.join(os.path.dirname(fname), v)
return conf
@staticmethod
def set_torch_seed(random_seed: int):
import torch
torch.manual_seed(random_seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(random_seed)
torch.cuda.manual_seed_all(random_seed)
np.random.seed(random_seed)
random.seed(random.seed)
os.environ['PYTHONHASHSEED'] = str(random_seed)
@staticmethod
def load_numpy_random_state(result: Dict[str, Any]) -> None:
random_state = result.get("random_state")
if random_state is not None:
random.setstate(random_state)
np_rand_state = result.get("np_rand_state")
if np_rand_state is not None:
np.random.set_state(np_rand_state)
@staticmethod
def save_numpy_random_state() -> Dict[str, Any]:
result = {
"random_state": random.getstate(),
"numpy_random_state": np.random.get_state(),
}
return result
@staticmethod
def mirror_name_list(name_list: List[str]):
indices = [i for i in range(len(name_list))]
def index(name):
try:
return name_list.index(name)
except ValueError:
return -1
for i, n in enumerate(name_list):
# rule 1: left->right
idx = -1
if n.find('left') == 0:
idx = index('right' + n[4:])
elif n.find('Left') == 0:
idx = index('Right' + n[4:])
elif n.find('LEFT') == 0:
idx = index('RIGHT' + n[4:])
elif n.find('right') == 0:
idx = index('left' + n[5:])
elif n.find('Right') == 0:
idx = index('Left' + n[5:])
elif n.find('RIGHT') == 0:
idx = index('LEFT' + n[5:])
elif n.find('L') == 0:
idx = index('R' + n[1:])
elif n.find('l') == 0:
idx = index('r' + n[1:])
elif n.find('R') == 0:
idx = index('L' + n[1:])
elif n.find('r') == 0:
idx = index('l' + n[1:])
indices[i] = idx if idx >= 0 else i
return indices
class RotateType(IntEnum):
Matrix = 1
AxisAngle = 2
Vec6d = 3
SVD9d = 4
Quaternion = 5
class MathHelper:
unit_vec6d = np.array([
1.0, 0.0,
0.0, 1.0,
0.0, 0.0
], dtype=np.float64)
@staticmethod
def count_ones(x: int) -> int:
count: int = 0
while x > 0:
if x & 1 == 1:
count += 1
x >>= 1
return count
@staticmethod
def array_distance(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
input: m x 2, n x 2
output: m x n
"""
m, k = arr1.shape
n, k = arr2.shape
arr1_power: np.ndarray = arr1 ** 2
arr1_power_sum: np.ndarray = np.sum(arr1_power, axis=1)
arr1_power_sum: np.ndarray = np.tile(arr1_power_sum, (n, 1))
arr1_power_sum: np.ndarray = arr1_power_sum.T
arr2_power: np.ndarray = arr2 ** 2
arr2_power_sum: np.ndarray = np.sum(arr2_power, axis=-1)
arr2_power_sum: np.ndarray = np.tile(arr2_power_sum, (m, 1))
dis: np.ndarray = arr1_power_sum + arr2_power_sum - (2 * np.dot(arr1, arr2.T))
dis: np.ndarray = np.sqrt(dis)
def test_func():
test_dis = np.zeros((m, n))
for i in range(m):
for j in range(n):
test_dis[i, j] = np.linalg.norm(arr1[i] - arr2[j])
print(np.max(test_dis - dis))
# test_func()
return dis
@staticmethod
def quat_from_other_rotate(x: np.ndarray, rotate_type) -> np.ndarray:
if rotate_type == Common.RotateType.Matrix or rotate_type == Common.RotateType.SVD9d:
return Common.MathHelper.matrix_to_quat(x)
elif rotate_type == Common.RotateType.Quaternion:
return x
elif rotate_type == Common.RotateType.AxisAngle:
return Common.MathHelper.quat_from_axis_angle(x)
elif rotate_type == Common.RotateType.Vec6d:
return Common.MathHelper.vec6d_to_quat(x)
else:
raise NotImplementedError
@staticmethod
def quat_to_other_rotate(quat: np.ndarray, rotate_type):
if rotate_type == Common.RotateType.SVD9d or rotate_type == Common.RotateType.Matrix:
return Common.MathHelper.quat_to_matrix(quat)
elif rotate_type == Common.RotateType.Vec6d:
return Common.MathHelper.quat_to_vec6d(quat)
elif rotate_type == Common.RotateType.Quaternion:
return quat
elif rotate_type == Common.RotateType.AxisAngle:
return Common.MathHelper.quat_to_axis_angle(quat)
else:
raise NotImplementedError
@staticmethod
def get_rotation_dim(rotate_type):
if rotate_type == Common.RotateType.Vec6d:
return 6
elif rotate_type == Common.RotateType.AxisAngle:
return 3
elif rotate_type == Common.RotateType.SVD9d:
return 9
elif rotate_type == Common.RotateType.Matrix:
return 9
elif rotate_type == Common.RotateType.Quaternion:
return 4
else:
raise NotImplementedError
@staticmethod
def get_rotation_last_shape(rotate_type) -> Tuple:
if rotate_type == Common.RotateType.Vec6d:
last_shape = (3, 2)
elif rotate_type == Common.RotateType.AxisAngle:
last_shape = (3,)
elif rotate_type == Common.RotateType.SVD9d:
last_shape = (3, 3)
elif rotate_type == Common.RotateType.Matrix:
last_shape = (3, 3)
elif rotate_type == Common.RotateType.Quaternion:
last_shape = (4,)
else:
raise NotImplementedError
return last_shape
@staticmethod
def quat_multiply(p: np.ndarray, q: np.ndarray) -> np.ndarray:
"""
multiply 2 quaternions. p.shape == q.shape
"""
assert 2 == len(p.shape) and 4 == p.shape[-1]
assert 2 == len(q.shape) and 4 == q.shape[-1]
w: np.ndarray = p[:, 3:4] * q[:, 3:4] - np.sum(p[:, :3] * q[:, :3], axis=1, keepdims=True)
xyz: np.ndarray = p[:, None, 3] * q[:, :3] + q[:, None, 3] * p[:, :3] + np.cross(p[:, :3], q[:, :3], axis=1)
return np.concatenate([xyz, w], axis=-1)
@staticmethod
def quat_integrate(q: np.ndarray, omega: np.ndarray, dt: float):
"""
update quaternion, q_{t+1} = normalize(q_{t} + 0.5 * w * q_{t})
"""
init_q_shape = q.shape
if q.shape[-1] == 1 and omega.shape[-1] == 1:
q = q.reshape(q.shape[:-1])
omega = omega.reshape(omega.shape[:-1])
assert 4 == q.shape[-1] and 3 == omega.shape[-1]
omega = np.concatenate([omega, np.zeros(omega.shape[:-1] + (1,))], axis=-1)
delta_q = 0.5 * dt * Common.MathHelper.quat_multiply(omega, q)
result = q + delta_q
result /= np.linalg.norm(result, axis=-1, keepdims=True)
return result.reshape(init_q_shape)
@staticmethod
def quat_to_matrix(q: np.ndarray) -> np.ndarray:
assert q.shape[-1] == 4
return Rotation(q.reshape(-1, 4), copy=False, normalize=False).as_matrix().reshape(q.shape[:-1] + (3, 3))
@staticmethod
def matrix_to_quat(mat: np.ndarray) -> np.ndarray:
assert mat.shape[-2:] == (3, 3)
return Rotation.from_matrix(mat.reshape((-1, 3, 3))).as_quat().reshape(mat.shape[:-2] + (4,))
@staticmethod
def quat_to_vec6d(q: np.ndarray) -> np.ndarray:
"""
input quaternion in shape (..., 4)
return: in shape (..., 3, 2)
"""
assert q.shape[-1] == 4
mat: np.ndarray = Rotation(q.reshape(-1, 4)).as_matrix() # shape == (N, 3, 3)
mat: np.ndarray = mat.reshape(q.shape[:-1] + (3, 3))
return mat[..., :2]
@staticmethod
def vec6d_to_quat(x: np.ndarray, normalize: bool = True) -> np.ndarray:
"""
input 6d vector in shape (..., 3, 2)
return in shape (..., 4)
"""
assert x.shape[-2:] == (3, 2)
if normalize:
x = x / np.linalg.norm(x, axis=-2, keepdims=True)
last_col: np.ndarray = np.cross(x[..., 0], x[..., 1], axis=-1)
last_col = last_col / np.linalg.norm(last_col, axis=-1, keepdims=True)
mat = np.concatenate([x, last_col[..., None]], axis=-1)
quat: np.ndarray = Rotation.from_matrix(mat.reshape((-1, 3, 3))).as_quat().reshape(x.shape[:-2] + (4,))
return quat
@staticmethod
def normalize_angle(a: np.ndarray) -> np.ndarray:
"""
Covert angles to [-pi, pi)
"""
res: np.ndarray = a.copy()
res[res >= np.pi] -= 2 * np.pi
res[res < np.pi] += 2 * np.pi
return res
@staticmethod
def normalize_vec(a: np.ndarray) -> np.ndarray:
norm = np.linalg.norm(a, axis=-1, keepdims=True)
norm[norm == 0] = 1
return a / norm
@staticmethod
def up_vector() -> np.ndarray:
"""
return (0, 1, 0)
"""
return np.array([0.0, 1.0, 0.0])
@staticmethod
def ego_forward_vector() -> np.ndarray:
"""
return (0, 0, 1)
"""
return np.array([0.0, 0.0, 1.0])
@staticmethod
def unit_vector(axis: int) -> np.ndarray: # shape == (3,)
res = np.zeros(3)
res[axis] = 1
return res
@staticmethod
def unit_quat_scipy() -> np.ndarray: # shape == (4,)
return Common.MathHelper.unit_quat()
@staticmethod
def unit_quat_scipy_list() -> List[float]:
return [0.0, 0.0, 0.0, 1.0]
@staticmethod
def quat_from_scipy_to_ode(q: np.ndarray) -> np.ndarray:
return Common.MathHelper.xyzw_to_wxyz(q)
@staticmethod
def quat_from_ode_to_scipy(q: np.ndarray) -> np.ndarray:
return Common.MathHelper.wxyz_to_xyzw(q)
@staticmethod
def quat_from_ode_to_unity(q: np.ndarray) -> np.ndarray:
return Common.MathHelper.wxyz_to_xyzw(q)
@staticmethod
def unit_quat_ode() -> np.ndarray:
return np.array(Common.MathHelper.unit_quat_ode_list())
@staticmethod
def unit_quat_ode_list() -> List[float]:
return [1.0, 0.0, 0.0, 0.0]
@staticmethod
def unit_quat_unity() -> np.ndarray:
return np.asarray(Common.MathHelper.unit_quat_unity_list())
@staticmethod
def unit_quat_unity_list() -> List[float]:
return [0.0, 0.0, 0.0, 1.0]
@staticmethod
def unit_quat() -> np.ndarray:
return np.array([0.0, 0.0, 0.0, 1.0])
@staticmethod
def unit_quat_arr(shape: Union[int, Iterable, Tuple[int]]) -> np.ndarray:
if type(shape) == int:
shape = (shape, 4)
res = np.zeros(shape, dtype=np.float64)
res[..., -1] = 1
return res.reshape(shape)
@staticmethod
def ode_quat_to_rot_mat(q: np.ndarray) -> np.ndarray:
return Rotation(Common.MathHelper.quat_from_ode_to_scipy(q)).as_matrix()
@staticmethod
def rot_mat_to_ode_quat(mat: np.ndarray) -> np.ndarray:
return Common.MathHelper.quat_from_scipy_to_ode(Rotation.from_matrix(mat).as_quat())
@staticmethod
def vec_diff(v_in: np.ndarray, forward: bool, fps: float):
v = np.empty_like(v_in)
frag = v[:-1] if forward else v[1:]
frag[:] = np.diff(v_in, axis=0) * fps
v[-1 if forward else 0] = v[-2 if forward else 1]
return v
@staticmethod
def vec_axis_to_zero(v: np.ndarray, axis: Union[int, List[int], np.ndarray]) -> np.ndarray:
res: np.ndarray = v.copy()
res[..., axis] = 0
return res
@staticmethod
def xz_vector_to_xyz(xz: np.ndarray) -> np.ndarray:
xyz = np.zeros((xz.shape[:-1] + (3,)))
xyz[..., [0, 2]] = xz
return xyz
@staticmethod
def flip_quat_by_w(q: np.ndarray) -> np.ndarray:
res = q.copy()
idx: np.ndarray = res[..., -1] < 0
res[idx, :] = -res[idx, :]
return res
@staticmethod
def flip_quat_arr_by_w(*args):
return [Common.MathHelper.flip_quat_by_w(i) for i in args]
@staticmethod
def flip_vector_by_dot(x: np.ndarray, inplace: bool = False) -> np.ndarray:
"""
make sure x[i] * x[i+1] >= 0
"""
if x.ndim == 1:
return x
sign: np.ndarray = np.sum(x[:-1] * x[1:], axis=-1)
sign[sign < 0] = -1
sign[sign >= 0] = 1
sign = np.cumprod(sign, axis=0, )
x_res = x.copy() if not inplace else x
x_res[1:][sign < 0] *= -1
return x_res
@staticmethod
def flip_vec3_by_dot(x: np.ndarray, inplace: bool = False) -> np.ndarray:
assert x.shape[-1] == 3
return Common.MathHelper.flip_vector_by_dot(x, inplace)
@staticmethod
def flip_quat_by_dot(q: np.ndarray, inplace: bool = False) -> np.ndarray:
if q.shape[-1] != 4:
raise ValueError
return Common.MathHelper.flip_vector_by_dot(q, inplace)
@staticmethod
def flip_quat_arr_by_dot(*args) -> List[np.ndarray]:
return [Common.MathHelper.flip_quat_by_dot(i) for i in args]
@staticmethod
def flip_quat_pair_by_dot(q0s: np.ndarray, q1s: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
q0 will not be changed.
q1 will be flipped to the same semi sphere as q0
"""
assert q0s.shape[-1] == 4
assert q1s.shape == q0s.shape
dot_value = np.sum(q0s * q1s, axis=-1, keepdims=True) < 0
dot_res = np.concatenate([dot_value] * 4, axis=-1)
q1: np.ndarray = q1s.copy()
q1[dot_res] = -q1[dot_res]
return q0s, q1
@staticmethod
def quat_equal(q1: np.ndarray, q2: np.ndarray) -> bool:
return np.all(np.abs(Common.MathHelper.flip_quat_by_w(q1) - Common.MathHelper.flip_quat_by_w(q2)) < 1e-5)
@staticmethod
def proj_vec_to_plane(a: np.ndarray, v: np.ndarray):
"""
Project Vector to Plane
:param a: original vector
:param v: Normal vector of Plane
:return: a_new(result of projection)
"""
# k: coef.
# a_new = a - k * v
# a_new * v = 0
# Solution: k = (a * v) / (v * v)
k: np.ndarray = np.sum(a * v, axis=-1) / np.sum(v * v, axis=-1) # (N, )
return a - np.repeat(k, 3).reshape(v.shape) * v
@staticmethod
def proj_multi_vec_to_a_plane(a_arr: np.ndarray, v: np.ndarray):
v_arr = np.zeros_like(a_arr)
v_arr[:, :] = v
return Common.MathHelper.proj_vec_to_plane(a_arr, v_arr)
@staticmethod
def quat_between(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Rotation from vector a to vector b
:param a: (n, 3) vector
:param b: (n, 3) vector
:return: (n, 4) quaternion
"""
cross_res = np.cross(a, b)
w_ = np.sqrt((a ** 2).sum(axis=-1) * (b ** 2).sum(axis=-1)) + (a * b).sum(axis=-1)
res_ = np.concatenate([cross_res, w_[..., np.newaxis]], axis=-1)
return res_ / np.linalg.norm(res_, axis=-1, keepdims=True)
@staticmethod
def quat_to_axis_angle(q: np.ndarray, normalize=True, copy=True):
assert q.shape[-1] == 4
return Rotation(q.reshape((-1, 4)), normalize=normalize, copy=copy).as_rotvec().reshape(q.shape[:-1] + (3, ))
@staticmethod
def quat_from_axis_angle(axis: np.ndarray, angle: Optional[np.ndarray] = None, normalize: bool = False) -> np.ndarray:
if angle is not None:
assert axis.shape == angle.shape + (3,)
if normalize:
axis: np.ndarray = axis / np.linalg.norm(axis, axis=-1, keepdims=True)
angle: np.ndarray = (0.5 * angle)[..., None]
sin_res: np.ndarray = np.sin(angle)
cos_res: np.ndarray = np.cos(angle)
result = np.concatenate([axis * sin_res, cos_res], axis=-1)
return result
else:
return Rotation.from_rotvec(axis.reshape((-1, 3))).as_quat().reshape(axis.shape[:-1] + (4,))
@staticmethod
def log_quat(q: np.ndarray) -> np.ndarray:
"""
log quaternion。
:param q: (n, 4) quaternion
:return:
"""
if q.shape[-1] != 4:
raise ArithmeticError
if q.ndim > 1:
return 0.5 * Rotation(q.reshape(-1, 4), copy=False).as_rotvec().reshape(q.shape[:-1] + (3,))
else:
return 0.5 * Rotation(q, copy=False).as_rotvec()
@staticmethod
def exp_to_quat(v: np.ndarray) -> np.ndarray:
"""
:param v:
:return:
"""
# Note that q and -q is the same rotation. so result is not unique
if v.shape[-1] != 3:
raise ArithmeticError
if v.ndim > 1:
return Rotation.from_rotvec(2 * v.reshape(-1, 3)).as_quat().reshape(v.shape[:-1] + (4,))
else:
return Rotation.from_rotvec(2 * v).as_quat()
@staticmethod
def xyzw_to_wxyz(q: np.ndarray) -> np.ndarray:
return np.concatenate([q[..., 3:4], q[..., 0:3]], axis=-1)
@staticmethod
def wxyz_to_xyzw(q: np.ndarray) -> np.ndarray:
return np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1)
@staticmethod
def facing_decompose(q: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
return: ry, facing. ry only has y component, and facing only has (x, z) component.
"""
return Common.MathHelper.y_decompose(q)
@staticmethod
def extract_heading_Y_up(q: np.ndarray):
""" extract the rotation around Y axis from given quaternions
note the quaterions should be {(x,y,z,w)}
"""
q = np.asarray(q)
shape = q.shape
q = q.reshape(-1, 4)
v = Rotation(q, normalize=False, copy=False).as_matrix()[:, :, 1]
# axis=np.cross(v,(0,1,0))
axis = v[:, (2, 1, 0)]
axis *= [-1, 0, 1]
norms = np.linalg.norm(axis, axis=-1)
scales = np.empty_like(norms)
small_angle = (norms <= 1e-3)
large_angle = ~small_angle
scales[small_angle] = norms[small_angle] + norms[small_angle] ** 3 / 6
scales[large_angle] = np.arccos(v[large_angle, 1]) / norms[large_angle]
correct = Rotation.from_rotvec(axis * scales[:, None])
heading = (correct * Rotation(q, normalize=False, copy=False)).as_quat()
heading[heading[:, -1] < 0] *= -1
return heading.reshape(shape)
@staticmethod
def decompose_rotation(q: np.ndarray, vb: np.ndarray):
rot_q = Rotation(q, copy=False)
va = rot_q.apply(vb)
va /= np.linalg.norm(va, axis=-1, keepdims=True)
rot_axis = np.cross(va, vb)
rot_axis_norm = np.linalg.norm(rot_axis, axis=-1, keepdims=True)
rot_axis_norm[rot_axis_norm < 1e-14] = 1e-14
rot_axis /= rot_axis_norm
rot_angle = np.asarray(-np.arccos(np.clip(va.dot(vb), -1, 1))).reshape(-1)
# TODO: minus or plus..?
if rot_axis.ndim > 1:
rot_angle = rot_angle.reshape(-1, 1)
ret_result: np.ndarray = (Rotation.from_rotvec(rot_angle * (-rot_axis)) * rot_q).as_quat()
ret_result: np.ndarray = Common.MathHelper.flip_quat_by_dot(ret_result)
return ret_result
@staticmethod
def axis_decompose(q: np.ndarray, axis: np.ndarray):
"""
return:
res: rotation along axis
r_other:
"""
assert axis.ndim == 1 and axis.shape[0] == 3
res = Common.MathHelper.decompose_rotation(q, np.asarray(axis))
r_other = (Rotation(res, copy=False, normalize=False).inv() * Rotation(q, copy=False, normalize=False)).as_quat()
r_other = Common.MathHelper.flip_quat_by_dot(r_other)
res[np.abs(res) < 1e-14] = 0
r_other[np.abs(r_other) < 1e-14] = 0
res /= np.linalg.norm(res, axis=-1, keepdims=True)
r_other /= np.linalg.norm(r_other, axis=-1, keepdims=True)
return res, r_other
@staticmethod
def x_decompose(q: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
return Common.MathHelper.axis_decompose(q, np.array([1.0, 0.0, 0.0]))
@staticmethod
def y_decompose(q: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
return Common.MathHelper.axis_decompose(q, np.array([0.0, 1.0, 0.0]))
@staticmethod
def z_decompose(q: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
return Common.MathHelper.axis_decompose(q, np.array([0.0, 0.0, 1.0]))
@staticmethod
def resample_joint_linear(x: np.ndarray, ratio: int, old_fps: int):
old_frame: int = x.shape[0]
new_frame: int = old_frame * ratio
new_fps: int = old_fps * ratio
result: np.ndarray = np.zeros((new_frame,) + x.shape[1:])
nj: int = x.shape[1]
ticks = np.arange(0, old_frame, dtype=np.float64) / old_fps
new_ticks = np.arange(0, new_frame, dtype=np.float64) / new_fps
for index in range(nj):
j_interp = interp1d(ticks, x[:, index], kind='linear', axis=0, copy=True, bounds_error=False, assume_sorted=True)
result[:, index] = j_interp(new_ticks)
return result
@staticmethod
def slerp(q0s: np.ndarray, q1s: np.ndarray, t: Union[float, np.ndarray], eps: float = 1e-7):
q0s = q0s.reshape((1, 4)) if q0s.shape == (4,) else q0s
q1s = q1s.reshape((1, 4)) if q1s.shape == (4,) else q1s
assert q0s.shape[-1] == 4 and q0s.ndim == 2 and q0s.shape == q1s.shape
is_ndarray = isinstance(t, np.ndarray)
assert not is_ndarray or t.size == q0s.shape[0]
t = t.reshape((-1, 1)) if is_ndarray else t
# filp by dot
q0, q1 = Common.MathHelper.flip_quat_pair_by_dot(q0s, q1s) # (n, 4), (n, 4)
if np.allclose(q0, q1):
return q0
theta = np.arccos(np.sum(q0 * q1, axis=-1)) # (n,)
res = Common.MathHelper.unit_quat_arr(q0.shape) # (n, 4)
small_flag: np.ndarray = np.abs(theta) < eps # (small,)
small_idx = np.argwhere(small_flag).flatten() # (small,)
t_small = t[small_idx] if is_ndarray else t # (small, 1) or float
res[small_idx] = (1.0 - t_small) * q0[small_idx] + t_small * q1[small_idx] # (small, 4)
res[small_idx] /= np.linalg.norm(res[small_idx], axis=-1, keepdims=True) # (small, 4)
plain_idx: np.ndarray = np.argwhere(~small_flag).flatten() # (plain,)
theta_plain = theta[plain_idx, None] # (plain, 1)
inv_sin_theta = 1.0 / np.sin(theta_plain) # (plain, 1)
t_plain = t[plain_idx] if is_ndarray else t # (plain, 1) or float
res[plain_idx] = (np.sin((1.0 - t_plain) * theta_plain) * inv_sin_theta) * q0[plain_idx] + \
(np.sin(t_plain * theta_plain) * inv_sin_theta) * q1[plain_idx] # (plain, 4)
res = np.ascontiguousarray(res / np.linalg.norm(res, axis=-1, keepdims=True))
return res
@staticmethod
def average_quat_by_slerp(qs: List[np.ndarray]) -> np.ndarray:
result: np.ndarray = qs[0].copy()
len_qs: int = len(qs)
for i in range(1, len_qs):
ratio: float = float(i) / (i + 1)
result: np.ndarray = Common.MathHelper.slerp(result, qs[i], ratio)
return result
@staticmethod
def torch_skew(v):
'''
:param v : torch.Tensor [3,1] or [1,3]
this function will return the skew matrix (cross product matrix) of a vector
be sure that it has ONLY 3 element
it can be autograd
'''
import torch
skv = torch.diag(torch.flatten(v)).roll(1, 1).roll(-1, 0)
return skv - skv.transpose(0, 1)
@staticmethod
def cross_mat(v):
"""create cross-product matrix for v
Args:
v (torch.Tensor): a vector with shape (..., 3, 1)
"""
import torch
mat = torch.stack((
torch.zeros_like(v[..., 0, :]), -v[..., 2, :], v[..., 1, :],
v[..., 2, :], torch.zeros_like(v[..., 1, :]), -v[..., 0, :],
-v[..., 1, :], v[..., 0, :], torch.zeros_like(v[..., 2, :])
), dim=-1).view(*v.shape[:-2], 3, 3)
return mat
@staticmethod
def np_skew(v: np.ndarray):
return np.array([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]
], dtype=np.float64)
class RotateConvertFast:
@staticmethod
def quat_single_to_other_rotate(x: np.ndarray, rotate_type) -> np.ndarray:
pass
@staticmethod
def quat_single_from_other_rotate(x: np.ndarray, rotate_type) -> np.ndarray:
pass
@staticmethod
def quat_to_other_rotate(x: np.ndarray, rotate_type) -> np.ndarray:
x: np.ndarray = np.ascontiguousarray(x, dtype=np.float64)
if rotate_type == Common.RotateType.Matrix or rotate_type == Common.RotateType.SVD9d:
return quat_to_matrix_fast(x)
elif rotate_type == Common.RotateType.Quaternion:
return x
elif rotate_type == Common.RotateType.AxisAngle:
return quat_to_rotvec_fast(x)[1]
elif rotate_type == Common.RotateType.Vec6d:
return quat_to_vec6d_fast(x)
else:
raise NotImplementedError
@staticmethod
def quat_from_other_rotate(x: np.ndarray, rotate_type) -> np.ndarray:
q: np.ndarray = np.ascontiguousarray(x, dtype=np.float64)
if rotate_type == Common.RotateType.Matrix or rotate_type == Common.RotateType.SVD9d:
raise NotImplementedError
elif rotate_type == Common.RotateType.Quaternion:
return q
elif rotate_type == Common.RotateType.AxisAngle:
return quat_from_rotvec_fast(q)
elif rotate_type == Common.RotateType.Vec6d:
return six_dim_mat_to_quat_fast(q)
else:
raise NotImplementedError
class SmoothOperator:
class SmoothMode(IntEnum):
NO = 0 # not using smooth
GAUSSIAN = 1 # use gaussian smooth
BUTTER_WORTH = 2 # use butter worth smooth
class GaussianBase:
__slots__ = ("width",)
def __init__(self, width: Optional[int]):
self.width: Optional[int] = width
class FilterInfoBase:
__slots__ = ("order", "wn")
def __init__(self, order: int, cut_off_freq: float, sample_freq: int):
self.order = order
self.wn = self.calc_freq(cut_off_freq, sample_freq)
@classmethod
def build_from_dict(cls, info: Optional[Dict[str, Any]], sample_freq: int):
return cls(info["order"], info["cut_off_freq"], sample_freq) if info is not None else None
@staticmethod
def calc_freq(cut_off_freq: float, sample_freq: float) -> float:
return cut_off_freq / (sample_freq / 2)
class ButterWorthBase(FilterInfoBase):
__slots__ = ("order", "wn")
def __init__(self, order: int, cut_off_freq: float, sample_freq: int):
super().__init__(order, cut_off_freq, sample_freq)
@staticmethod
def smooth_operator(x: np.ndarray, smooth_type) -> np.ndarray:
"""
The first dimension of x is time
"""
# print(f"call smoother operator, smooth_type == {type(smooth_type)}")
if smooth_type is None:
result = x
elif isinstance(smooth_type, Common.SmoothOperator.GaussianBase):
if smooth_type.width is not None:
result = filters.gaussian_filter1d(x, smooth_type.width, axis=0, mode='nearest')
else:
result = x
elif isinstance(smooth_type, Common.SmoothOperator.ButterWorthBase):
b, a = signal.butter(smooth_type.order, smooth_type.wn)
result = signal.filtfilt(b, a, x, axis=0)
else:
raise NotImplementedError("Only support GaussianBase and ButterWorthBase.")
return result
class pymotionlib:
class Utils:
@staticmethod
def quat_product(p: np.ndarray, q: np.ndarray, inv_p: bool = False, inv_q: bool = False):
if p.shape[-1] != 4 or q.shape[-1] != 4:
raise ValueError('operands should be quaternions')
if len(p.shape) != len(q.shape):
if len(p.shape) == 1:
p.reshape([1] * (len(q.shape) - 1) + [4])
elif len(q.shape) == 1:
q.reshape([1] * (len(p.shape) - 1) + [4])
else:
raise ValueError('mismatching dimensions')
is_flat = len(p.shape) == 1
if is_flat:
p = p.reshape(1, 4)
q = q.reshape(1, 4)
product = np.empty([max(p.shape[i], q.shape[i]) for i in range(len(p.shape) - 1)] + [4],
dtype=np.result_type(p.dtype, q.dtype))
pw = p[..., 3] if not inv_p else -p[..., 3]
qw = q[..., 3] if not inv_q else -q[..., 3]
product[..., 3] = pw * qw - np.sum(p[..., :3] * q[..., :3], axis=-1)
product[..., :3] = (pw[..., None] * q[..., :3] + qw[..., None] * p[..., :3] +
np.cross(p[..., :3], q[..., :3]))
if is_flat:
product = product.reshape(4)
return product
@staticmethod
def flip_vector(vt: np.ndarray, normal: np.ndarray, inplace: bool):
vt = np.asarray(vt).reshape(-1, 3)
normal = np.asarray(normal).reshape(-1, 3)
if inplace:
vt -= (2 * np.sum(vt * normal, axis=-1, keepdims=True)) * normal
return vt
else:
return vt - (2 * np.sum(vt * normal, axis=-1, keepdims=True)) * normal
@staticmethod
def flip_quaternion(qt: np.ndarray, normal: np.ndarray, inplace: bool):
qt = np.asarray(qt).reshape(-1, 4)
normal = np.asarray(normal).reshape(-1, 3)
if not inplace:
qt = qt.copy()
pymotionlib.Utils.flip_vector(qt[:, :3], normal, True)
qt[:, -1] = -qt[:, -1]
return qt
@staticmethod
def align_angles(a: np.ndarray, degrees: bool, inplace: bool):
''' make the angles in the array continuous
we assume the first dim of a is the time
'''
step = 360. if degrees else np.pi * 2
a = np.asarray(a)
diff = np.diff(a, axis=0)
num_steps = np.round(diff / step)
num_steps = np.cumsum(num_steps, axis=0)
if not inplace:
a = a.copy()
a[1:] -= num_steps * step
return a
@staticmethod
def align_quaternion(qt: np.ndarray, inplace: bool):
''' make q_n and q_n+1 in the same semisphere
the first axis of qt should be the time
'''
qt = np.asarray(qt)
if qt.shape[-1] != 4:
raise ValueError('qt has to be an array of quaterions')
if not inplace:
qt = qt.copy()
if qt.size == 4: # do nothing since there is only one quation
return qt
sign = np.sum(qt[:-1] * qt[1:], axis=-1)
sign[sign < 0] = -1
sign[sign >= 0] = 1
sign = np.cumprod(sign, axis=0, )
qt[1:][sign < 0] *= -1
return qt
"""
@staticmethod
def extract_heading_Y_up(q: np.ndarray):
# extract the rotation around Y axis from given quaternions note the quaterions should be {(x,y,z,w)}
q = np.asarray(q)
shape = q.shape
q = q.reshape(-1, 4)
v = R(q, normalize=False, copy=False).as_matrix()[:, :, 1]
# axis=np.cross(v,(0,1,0))
axis = v[:, (2, 1, 0)]
axis *= [-1, 0, 1]
norms = np.linalg.norm(axis, axis=-1)
scales = np.empty_like(norms)
small_angle = (norms <= 1e-3)
large_angle = ~small_angle