/
math.py
1938 lines (1637 loc) · 54.3 KB
/
math.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
from __future__ import absolute_import
import math
from math import acos
from math import asin
from math import atan2
from math import cos
from math import pi
from math import sin
import warnings
import numpy as np
# epsilon for testing whether a number is close to zero
_EPS = np.finfo(float).eps * 4.0
_AXIS_VECTORS = {
'x': np.array([1, 0, 0]),
'y': np.array([0, 1, 0]),
'z': np.array([0, 0, 1]),
'-x': np.array([-1, 0, 0]),
'-y': np.array([0, -1, 0]),
'-z': np.array([0, 0, -1]),
'xy': np.array([1, 1, 0]),
'yx': np.array([1, 1, 0]),
'yz': np.array([0, 1, 1]),
'zy': np.array([0, 1, 1]),
'zx': np.array([1, 0, 1]),
'xz': np.array([1, 0, 1]),
}
def convert_to_axis_vector(axis):
"""Convert axis to float vector.
Parameters
----------
axis : list or numpy.ndarray or str or bool or None
rotation axis indicated by number or string.
Returns
-------
axis : numpy.ndarray
conveted axis
Examples
--------
>>> from skrobot.coordinates.math import convert_to_axis_vector
>>> convert_to_axis_vector('x')
array([1, 0, 0])
>>> convert_to_axis_vector('y')
array([0, 1, 0])
>>> convert_to_axis_vector('z')
array([0, 0, 1])
>>> convert_to_axis_vector('xy')
array([1, 1, 0])
>>> convert_to_axis_vector([1, 1, 1])
array([1, 1, 1])
>>> convert_to_axis_vector(True)
array([0, 0, 0])
>>> convert_to_axis_vector(False)
array([1, 1, 1])
"""
if isinstance(axis, str):
try:
return _AXIS_VECTORS[axis]
except KeyError:
raise NotImplementedError(
"Axis conversion for '{}' is not implemented.".format(axis))
elif isinstance(axis, list):
if len(axis) != 3:
raise ValueError("Axis list must have exactly three elements.")
return np.array(axis)
elif isinstance(axis, np.ndarray):
if axis.shape != (3,):
raise ValueError("Axis ndarray must be of shape (3,).")
return axis
elif isinstance(axis, bool):
# If True, returns a zero vector; if False, returns a ones vector
return np.zeros(3) if axis else np.ones(3)
elif axis is None:
return np.ones(3)
else:
raise ValueError("Invalid type for axis. "
"Must be one of: str, list, ndarray, bool, None.")
def _wrap_axis(axis):
warnings.warn(
'Function `_wrap_axis` is deprecated. '
'Please use `convert_to_axis_vector` instead',
DeprecationWarning)
return convert_to_axis_vector(axis)
def to_numpy_array(arr):
if isinstance(arr, (list, tuple)):
return np.array(arr)
elif isinstance(arr, np.ndarray):
return arr
else:
raise TypeError("Input must be a list, tuple, or numpy.ndarray.")
def _check_valid_rotation(rotation):
"""Checks that the given rotation matrix is valid."""
rotation = np.array(rotation)
if not isinstance(
rotation,
np.ndarray) or not np.issubdtype(
rotation.dtype,
np.number):
raise ValueError('Rotation must be specified as numeric numpy array')
if len(rotation.shape) != 2 or \
rotation.shape[0] != 3 or rotation.shape[1] != 3:
raise ValueError('Rotation must be specified as a 3x3 ndarray')
if np.abs(np.linalg.det(rotation) - 1.0) > 1e-3:
raise ValueError('Illegal rotation. Must have determinant == 1.0, '
'get {}'.format(np.linalg.det(rotation)))
return rotation
def _check_valid_translation(translation):
"""Checks that the translation vector is valid."""
if not isinstance(
translation,
np.ndarray) or not np.issubdtype(
translation.dtype,
np.number):
raise ValueError(
'Translation must be specified as numeric numpy array')
t = translation.squeeze()
if len(t.shape) != 1 or t.shape[0] != 3:
raise ValueError(
'Translation must be specified as a 3-vector, '
'3x1 ndarray, or 1x3 ndarray')
def wxyz2xyzw(quat):
"""Convert quaternion [w, x, y, z] to [x, y, z, w] order.
Parameters
----------
quat : list or numpy.ndarray
quaternion [w, x, y, z]
Returns
-------
quaternion : numpy.ndarray
quaternion [x, y, z, w]
Examples
--------
>>> from skrobot.coordinates.math import wxyz2xyzw
>>> wxyz2xyzw([1, 2, 3, 4])
array([2, 3, 4, 1])
"""
if isinstance(quat, (list, tuple)):
quat = np.array(quat)
return np.roll(quat, -1, axis=quat.ndim - 1)
def xyzw2wxyz(quat):
"""Convert quaternion [x, y, z, w] to [w, x, y, z] order.
Parameters
----------
quat : list or numpy.ndarray
quaternion [x, y, z, w]
Returns
-------
quaternion : numpy.ndarray
quaternion [w, x, y, z]
Examples
--------
>>> from skrobot.coordinates.math import xyzw2wxyz
>>> xyzw2wxyz([1, 2, 3, 4])
array([4, 1, 2, 3])
"""
if isinstance(quat, (list, tuple)):
quat = np.array(quat)
return np.roll(quat, 1, axis=quat.ndim - 1)
def triple_product(a, b, c):
"""Returns Triple Product
See https://en.wikipedia.org/wiki/Triple_product.
Geometrically, the scalar triple product
:math:`a\\cdot(b \\times c)`
is the (signed) volume of the parallelepiped defined
by the three vectors given.
Parameters
----------
a : numpy.ndarray
vector a
b : numpy.ndarray
vector b
c : numpy.ndarray
vector c
Returns
-------
triple product : float
calculated triple product
Examples
--------
>>> from skrobot.math import triple_product
>>> triple_product([1, 1, 1], [1, 1, 1], [1, 1, 1])
0
>>> triple_product([1, 0, 0], [0, 1, 0], [0, 0, 1])
1
"""
return np.dot(a, np.cross(b, c))
def sr_inverse(J, k=1.0, weight_vector=None):
"""Returns SR-inverse of given Jacobian.
Calculate Singularity-Robust Inverse
See: `Inverse Kinematic Solutions With Singularity Robustness \
for Robot Manipulator Control`
Parameters
----------
J : numpy.ndarray
jacobian
k : float
coefficients
weight_vector : None or numpy.ndarray
weight vector
Returns
-------
ret : numpy.ndarray
result of SR-inverse
"""
if J.ndim == 3:
return batch_sr_inverse(J, k, weight_vector=weight_vector)
r, _ = J.shape
# without weight
if weight_vector is None:
return sr_inverse_org(J, k)
# k=0 => sr-inverse = pseudo-inverse
if k == 0.0:
return np.linalg.pinv(J)
# with weight
weight_matrix = np.diag(weight_vector)
# umat = J W J^T + kI
# ret = W J^T (J W J^T + kI)^(-1)
weight_J = np.matmul(weight_matrix, J.T)
umat = np.matmul(J, weight_J) + k * np.eye(r)
ret = np.matmul(weight_J, np.linalg.inv(umat))
return ret
def sr_inverse_org(J, k=1.0):
"""Return SR-inverse of given J
Definition of SR-inverse is following.
:math:`J^* = J^T(JJ^T + kI_m)^{-1}`
Parameters
----------
J : numpy.ndarray
jacobian
k : float
coefficients
Returns
-------
sr_inverse : numpy.ndarray
calculated SR-inverse
"""
r, _ = J.shape
return np.matmul(J.T,
np.linalg.inv(np.matmul(J, J.T) + k * np.eye(r)))
def batch_sr_inverse(J_batch, k_values, weight_vector=None):
"""Compute the SR-inverse for a batch of Jacobian matrices.
This function computes the SR-inverse for each matrix in a batch by
applying a regularization term scaled by `k_values` and optionally
using a weighted pseudo-inverse if `weight_vector` is provided.
Parameters
----------
J_batch : ndarray
A 3D numpy array of shape (batch_size, r, c) where each
slice (J_batch[i]) represents a Jacobian matrix.
k_values : ndarray
A 1D numpy array of length batch_size, where each element
k_values[i] represents the regularization parameter
for the i-th matrix in the batch.
weight_vector : ndarray, optional
A 1D numpy array of length c (the number of columns in
each Jacobian matrix), which is used to create a diagonal
weight matrix W. If None, the identity matrix is used as
the weight matrix (default is None).
Returns
-------
ndarray
A 3D numpy array of shape (batch_size, c, r), where each slice
is the SR-inverse of the corresponding Jacobian matrix in the
input batch.
Notes
-----
The SR-inverse is computed using the formula:
(W*J^T*(J*W*J^T + k*I)^-1),
where J is the Jacobian matrix, W is the weight matrix
(either identity or derived from `weight_vector`),
J^T is the transpose of J, I is the identity matrix, and k
is the regularization parameter.
"""
batch_size, r, c = J_batch.shape
I = np.eye(r)
# Adjust k_values to be shape (batch_size, r, r) for broadcasting
k_matrix = k_values[:, np.newaxis, np.newaxis] * np.tile(
I, (batch_size, 1, 1))
if weight_vector is None:
W = np.eye(c)
else:
W = np.diag(weight_vector)
W = W.reshape((c, c))
J_T = J_batch.transpose(0, 2, 1)
weighted_J_T = np.matmul(W, J_T)
umat = np.matmul(J_batch, weighted_J_T) + k_matrix
umat_inv = np.linalg.inv(umat)
sr_inverse = np.matmul(weighted_J_T, umat_inv)
return sr_inverse
def jacobian_inverse(J, manipulability_limit=0.1,
manipulability_gain=0.001,
weight=None):
"""Calculate the pseudo-inverse or SR-inverse depending on manipulability.
"""
if J.ndim == 2: # Single Jacobian matrix
m = manipulability(J)
if m < manipulability_limit:
k = manipulability_gain * ((1.0 - m / manipulability_limit) ** 2)
else:
k = 0
return sr_inverse(J, k, weight)
batch_size, r, c = J.shape
# Calculate manipulability for each Jacobian
m = manipulability(J)
# Calculate k values for the entire batch based on manipulability
k_values = np.zeros(batch_size)
low_manipulability_mask = m < manipulability_limit
if np.any(low_manipulability_mask):
k_values[low_manipulability_mask] = manipulability_gain * (
(1.0 - m[low_manipulability_mask] / manipulability_limit) ** 2)
# Compute SR-inverse for the entire batch using calculated k values
sr_inverses = batch_sr_inverse(J, k_values, weight)
# Return single matrix or batch depending on input
return sr_inverses
def manipulability(J):
"""Compute manipulability for a single matrix or each matrix in a batch.
This function can handle both a single Jacobian matrix and a batch of
Jacobian matrices. For a single matrix, it returns the manipulability
as a float. For a batch, it returns an array of manipulability values.
Definition of manipulability is following.
:math:`w = \\sqrt{\\det J(\\theta)J^T(\\theta)}`
Parameters
----------
J : numpy.ndarray
Jacobian matrix or batch of Jacobian matrices. It should be of
shape (n, m) for a single matrix or (batch_size, n, m) for a batch.
Returns
-------
w : float
Manipulability or array of manipulability values.
"""
if J.ndim == 2: # Single matrix case
return np.sqrt(max(0.0, np.linalg.det(np.matmul(J, J.T))))
elif J.ndim == 3: # Batch of matrices
batch_size, _, _ = J.shape
JJT = np.matmul(J, np.transpose(J, axes=(0, 2, 1)))
det_JJT = np.linalg.det(JJT)
det_JJT = np.maximum(0.0, det_JJT) # Ensure non-negative before sqrt
w = np.sqrt(det_JJT)
return w
else:
raise ValueError("Input must be a 2D or 3D numpy array")
def midpoint(p, a, b):
"""Return midpoint
Parameters
----------
p : float
ratio of a:b
a : numpy.ndarray
vector
b : numpy.ndarray
vector
Returns
-------
midpoint : numpy.ndarray
midpoint
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import midpoint
>>> midpoint(0.5, np.ones(3), np.zeros(3))
>>> array([0.5, 0.5, 0.5])
"""
return a + (b - a) * p
def midrot(p, r1, r2):
"""Returns mid (or p) rotation matrix of given two matrix r1 and r2.
Parameters
----------
p : float
ratio of r1:r2
r1 : numpy.ndarray
3x3 rotation matrix
r2 : numpy.ndarray
3x3 rotation matrix
Returns
-------
r : numpy.ndarray
3x3 rotation matrix
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import midrot
>>> midrot(0.5,
np.eye(3),
np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]]))
array([[ 0.70710678, 0. , 0.70710678],
[ 0. , 1. , 0. ],
[-0.70710678, 0. , 0.70710678]])
>>> from skrobot.coordinates.math import rpy_angle
>>> np.rad2deg(rpy_angle(midrot(0.5,
np.eye(3),
np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])))[0])
array([ 0., 45., 0.])
"""
r1 = _check_valid_rotation(r1)
r2 = _check_valid_rotation(r2)
r = np.matmul(r1.T, r2)
omega = matrix_log(r)
r = matrix_exponent(omega, p)
return np.matmul(r1, r)
def transform(m, v):
"""Return transform m v
Parameters
----------
m : numpy.ndarray
3 x 3 rotation matrix.
v : numpy.ndarray or list
input vector.
Returns
-------
np.matmul(m, v) : numpy.ndarray
transformed vector.
"""
m = np.array(m)
v = np.array(v)
return np.matmul(m, v)
def rotation_matrix(theta, axis, skip_normalization=False):
"""Return the rotation matrix.
Return the rotation matrix associated with counterclockwise rotation
about the given axis by theta radians.
Parameters
----------
theta : float
radian
axis : str or list or numpy.ndarray
rotation axis such that 'x', 'y', 'z'
[0, 0, 1], [0, 1, 0], [1, 0, 0]
skip_normalization : bool
if `True`, skip normalization for axis.
Returns
-------
rot : numpy.ndarray
rotation matrix about the given axis by theta radians.
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rotation_matrix
>>> rotation_matrix(np.pi / 2.0, [1, 0, 0])
array([[ 1.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 0.00000000e+00, 2.22044605e-16, -1.00000000e+00],
[ 0.00000000e+00, 1.00000000e+00, 2.22044605e-16]])
>>> rotation_matrix(np.pi / 2.0, 'y')
array([[ 2.22044605e-16, 0.00000000e+00, 1.00000000e+00],
[ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00],
[-1.00000000e+00, 0.00000000e+00, 2.22044605e-16]])
"""
if not skip_normalization:
axis = convert_to_axis_vector(axis)
axis = axis / np.sqrt(np.dot(axis, axis))
a = np.cos(theta / 2.0)
b, c, d = -axis * np.sin(theta / 2.0)
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
[2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
[2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])
def rotate_vector(vec, theta, axis):
"""Rotate vector.
Rotate vec with respect to axis.
Parameters
----------
vec : list or numpy.ndarray
target vector
theta : float
rotation angle
axis : list or numpy.ndarray or str
axis of rotation.
Returns
-------
rotated_vec : numpy.ndarray
rotated vector.
Examples
--------
>>> from numpy import pi
>>> from skrobot.coordinates.math import rotate_vector
>>> rotate_vector([1, 0, 0], pi / 6.0, [1, 0, 0])
array([1., 0., 0.])
>>> rotate_vector([1, 0, 0], pi / 6.0, [0, 1, 0])
array([ 0.8660254, 0. , -0.5 ])
>>> rotate_vector([1, 0, 0], pi / 6.0, [0, 0, 1])
array([0.8660254, 0.5 , 0. ])
"""
rot = rotation_matrix(theta, axis)
rotated_vec = transform(rot, vec)
return rotated_vec
def rotate_matrix(matrix, theta, axis, world=None, skip_normalization=False):
if world is False or world is None:
return np.dot(
matrix,
rotation_matrix(theta, axis,
skip_normalization=skip_normalization))
return np.dot(
rotation_matrix(theta, axis, skip_normalization=skip_normalization),
matrix)
def rpy_matrix(az, ay, ax):
"""Return rotation matrix from yaw-pitch-roll
This function creates a new rotation matrix which has been
rotated ax radian around x-axis in WORLD, ay radian around y-axis in WORLD,
and az radian around z axis in WORLD, in this order. These angles can be
extracted by the rpy function.
Parameters
----------
az : float
rotated around z-axis(yaw) in radian.
ay : float
rotated around y-axis(pitch) in radian.
ax : float
rotated around x-axis(roll) in radian.
Returns
-------
r : numpy.ndarray
rotation matrix
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rpy_matrix
>>> yaw = np.pi / 2.0
>>> pitch = np.pi / 3.0
>>> roll = np.pi / 6.0
>>> rpy_matrix(yaw, pitch, roll)
array([[ 1.11022302e-16, -8.66025404e-01, 5.00000000e-01],
[ 5.00000000e-01, 4.33012702e-01, 7.50000000e-01],
[-8.66025404e-01, 2.50000000e-01, 4.33012702e-01]])
"""
r = rotation_matrix(ax, 'x')
r = rotate_matrix(r, ay, 'y', world=True)
r = rotate_matrix(r, az, 'z', world=True)
return r
def rpy_angle(matrix):
"""Decomposing a rotation matrix to yaw-pitch-roll.
Parameters
----------
matrix : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
rpy : tuple(numpy.ndarray, numpy.ndarray)
pair of rpy in yaw-pitch-roll order.
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rpy_matrix
>>> from skrobot.coordinates.math import rpy_angle
>>> yaw = np.pi / 2.0
>>> pitch = np.pi / 3.0
>>> roll = np.pi / 6.0
>>> rot = rpy_matrix(yaw, pitch, roll)
>>> rpy_angle(rot)
(array([1.57079633, 1.04719755, 0.52359878]),
array([ 4.71238898, 2.0943951 , -2.61799388]))
"""
if np.sqrt(matrix[1, 0] ** 2 + matrix[0, 0] ** 2) < _EPS:
a = 0.0
else:
a = np.arctan2(matrix[1, 0], matrix[0, 0])
sa = np.sin(a)
ca = np.cos(a)
b = np.arctan2(-matrix[2, 0], ca * matrix[0, 0] + sa * matrix[1, 0])
c = np.arctan2(sa * matrix[0, 2] - ca * matrix[1, 2],
-sa * matrix[0, 1] + ca * matrix[1, 1])
rpy = np.array([a, b, c])
a = a + np.pi
sa = np.sin(a)
ca = np.cos(a)
b = np.arctan2(-matrix[2, 0], ca * matrix[0, 0] + sa * matrix[1, 0])
c = np.arctan2(sa * matrix[0, 2] - ca * matrix[1, 2],
-sa * matrix[0, 1] + ca * matrix[1, 1])
return rpy, np.array([a, b, c])
def normalize_vector(v, ord=2):
"""Return normalized vector
Parameters
----------
v : list or numpy.ndarray
vector
ord : int (optional)
ord of np.linalg.norm
Returns
-------
v : numpy.ndarray
normalized vector
Examples
--------
>>> from skrobot.coordinates.math import normalize_vector
>>> normalize_vector([1, 1, 1])
array([0.57735027, 0.57735027, 0.57735027])
>>> normalize_vector([0, 0, 0])
array([0., 0., 0.])
"""
v = np.array(v, dtype=np.float64)
norm = np.linalg.norm(v, ord=ord)
if norm == 0:
return v
return v / norm
def matrix2quaternion(m):
"""Returns quaternion of given rotation matrix.
Parameters
----------
m : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
quaternion : numpy.ndarray
quaternion [w, x, y, z] order
Examples
--------
>>> import numpy
>>> from skrobot.coordinates.math import matrix2quaternion
>>> matrix2quaternion(np.eye(3))
array([1., 0., 0., 0.])
"""
m = np.array(m, dtype=np.float64)
if m.ndim == 2:
tr = m[0, 0] + m[1, 1] + m[2, 2]
if tr > 0:
S = math.sqrt(tr + 1.0) * 2
qw = 0.25 * S
qx = (m[2, 1] - m[1, 2]) / S
qy = (m[0, 2] - m[2, 0]) / S
qz = (m[1, 0] - m[0, 1]) / S
elif (m[0, 0] > m[1, 1]) and (m[0, 0] > m[2, 2]):
S = math.sqrt(1. + m[0, 0] - m[1, 1] - m[2, 2]) * 2
qw = (m[2, 1] - m[1, 2]) / S
qx = 0.25 * S
qy = (m[0, 1] + m[1, 0]) / S
qz = (m[0, 2] + m[2, 0]) / S
elif m[1, 1] > m[2, 2]:
S = math.sqrt(1. + m[1, 1] - m[0, 0] - m[2, 2]) * 2
qw = (m[0, 2] - m[2, 0]) / S
qx = (m[0, 1] + m[1, 0]) / S
qy = 0.25 * S
qz = (m[1, 2] + m[2, 1]) / S
else:
S = math.sqrt(1. + m[2, 2] - m[0, 0] - m[1, 1]) * 2
qw = (m[1, 0] - m[0, 1]) / S
qx = (m[0, 2] + m[2, 0]) / S
qy = (m[1, 2] + m[2, 1]) / S
qz = 0.25 * S
return np.array([qw, qx, qy, qz])
elif m.ndim == 3:
r1, r2, r3 = m[:, 0, :], m[:, 1, :], m[:, 2, :]
r11, r12, r13 = r1[:, 0], r1[:, 1], r1[:, 2]
r21, r22, r23 = r2[:, 0], r2[:, 1], r2[:, 2]
r31, r32, r33 = r3[:, 0], r3[:, 1], r3[:, 2]
q0 = 0.25 * (r11 + r22 + r33 + 1)
q1 = 0.25 * (r11 - r22 - r33 + 1)
q2 = 0.25 * (-r11 + r22 - r33 + 1)
q3 = 0.25 * (-r11 - r22 + r33 + 1)
q0[np.where(q0 < 0.0)] = 0.
q1[np.where(q1 < 0.0)] = 0.
q2[np.where(q2 < 0.0)] = 0.
q3[np.where(q3 < 0.0)] = 0.
q0 = np.sqrt(q0)
q1 = np.sqrt(q1)
q2 = np.sqrt(q2)
q3 = np.sqrt(q3)
ones = np.ones_like(r11)
aranges = np.arange(ones.shape[0])
signs_array = np.array([
[ones, np.sign(r32 - r23), np.sign(r13 - r31), np.sign(r21 - r12)],
[np.sign(r32 - r23), ones, np.sign(r21 + r12), np.sign(r13 + r31)],
[np.sign(r13 - r31), np.sign(r21 + r12), ones, np.sign(r32 + r23)],
[np.sign(r21 - r12), np.sign(r31 + r13), np.sign(r32 + r23), ones],
])
argmaxes = np.argmax(np.array([q0, q1, q2, q3]), axis=0)
signs = signs_array[:, argmaxes, aranges]
res = np.array([q0, q1, q2, q3]).T * signs.T
resq = res / np.linalg.norm(res, axis=1, keepdims=True)
return resq
else:
raise ValueError(
'Unsupported rotation matrix shape. '
'Supports rotation matrices of (N, 3, 3) and (3, 3).')
def quaternion2matrix(q, normalize=False):
"""Returns matrix of given quaternion.
Parameters
----------
quaternion : list or numpy.ndarray
quaternion [w, x, y, z] order
normalize : bool
if normalize is True, input quaternion is normalized.
Returns
-------
rot : numpy.ndarray
3x3 rotation matrix
Examples
--------
>>> import numpy
>>> from skrobot.coordinates.math import quaternion2matrix
>>> quaternion2matrix([1, 0, 0, 0])
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
"""
q = np.array(q)
if normalize:
q = quaternion_normalize(q)
else:
norm = quaternion_norm(q)
if not np.allclose(norm, 1.0):
raise ValueError("quaternion q's norm is not 1")
if q.ndim == 1:
q0 = q[0]
q1 = q[1]
q2 = q[2]
q3 = q[3]
m = np.zeros((3, 3))
m[0, 0] = q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3
m[0, 1] = 2 * (q1 * q2 - q0 * q3)
m[0, 2] = 2 * (q1 * q3 + q0 * q2)
m[1, 0] = 2 * (q1 * q2 + q0 * q3)
m[1, 1] = q0 * q0 - q1 * q1 + q2 * q2 - q3 * q3
m[1, 2] = 2 * (q2 * q3 - q0 * q1)
m[2, 0] = 2 * (q1 * q3 - q0 * q2)
m[2, 1] = 2 * (q2 * q3 + q0 * q1)
m[2, 2] = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3
elif q.ndim == 2:
m = np.zeros((q.shape[0], 3, 3), dtype=np.float64)
m[:, 0, 0] = q[:, 0] * q[:, 0] + \
q[:, 1] * q[:, 1] - q[:, 2] * q[:, 2] - q[:, 3] * q[:, 3]
m[:, 0, 1] = 2 * (q[:, 1] * q[:, 2] - q[:, 0] * q[:, 3])
m[:, 0, 2] = 2 * (q[:, 1] * q[:, 3] + q[:, 0] * q[:, 2])
m[:, 1, 0] = 2 * (q[:, 1] * q[:, 2] + q[:, 0] * q[:, 3])
m[:, 1, 1] = q[:, 0] * q[:, 0] - \
q[:, 1] * q[:, 1] + q[:, 2] * q[:, 2] - q[:, 3] * q[:, 3]
m[:, 1, 2] = 2 * (q[:, 2] * q[:, 3] - q[:, 0] * q[:, 1])
m[:, 2, 0] = 2 * (q[:, 1] * q[:, 3] - q[:, 0] * q[:, 2])
m[:, 2, 1] = 2 * (q[:, 2] * q[:, 3] + q[:, 0] * q[:, 1])
m[:, 2, 2] = q[:, 0] * q[:, 0] - \
q[:, 1] * q[:, 1] - q[:, 2] * q[:, 2] + q[:, 3] * q[:, 3]
return m
def matrix_log(m):
"""Returns matrix log of given rotation matrix, it returns [-pi, pi]
Parameters
----------
m : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
matrixlog : numpy.ndarray
vector of shape (3, )
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import matrix_log
>>> matrix_log(np.eye(3))
array([0., 0., 0.])
"""
# calc logarithm of quaternion
q = matrix2quaternion(m)
q_w = q[0]
q_xyz = q[1:]
theta = 2.0 * np.arctan(np.linalg.norm(q_xyz) / q_w)
if theta > np.pi:
theta = theta - 2.0 * np.pi
elif theta < - np.pi:
theta = theta + 2.0 * np.pi
return theta * normalize_vector(q_xyz)
def matrix_exponent(omega, p=1.0):
"""Returns exponent of given omega.
This function is similar to cv2.Rodrigues.
Convert rvec (which is log quaternion) to rotation matrix.
Parameters
----------
omega : list or numpy.ndarray
vector of shape (3,)
Returns
-------
rot : numpy.ndarray
exponential matrix of given omega
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import matrix_exponent
>>> matrix_exponent([1, 1, 1])
array([[ 0.22629564, -0.18300792, 0.95671228],
[ 0.95671228, 0.22629564, -0.18300792],
[-0.18300792, 0.95671228, 0.22629564]])
>>> matrix_exponent([1, 0, 0])
array([[ 1. , 0. , 0. ],
[ 0. , 0.54030231, -0.84147098],
[ 0. , 0.84147098, 0.54030231]])
"""
w = np.linalg.norm(omega)
amat = outer_product_matrix(normalize_vector(omega))
return np.eye(3) + np.sin(w * p) * amat + \
(1.0 - np.cos(w * p)) * np.matmul(amat, amat)
def outer_product_matrix(v):
"""Returns outer product matrix of given v.
Returns following outer product matrix.
.. math::
\\left(
\\begin{array}{ccc}
0 & -v_2 & v_1 \\\\
v_2 & 0 & -v_0 \\\\
-v_1 & v_0 & 0
\\end{array}
\\right)
Parameters
----------
v : numpy.ndarray or list
[x, y, z]
Returns
-------
matrix : numpy.ndarray
3x3 rotation matrix.
Examples
--------
>>> from skrobot.coordinates.math import outer_product_matrix
>>> outer_product_matrix([1, 2, 3])
array([[ 0, -3, 2],
[ 3, 0, -1],
[-2, 1, 0]])
"""
return np.array([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]])
def cross_product(a, b):
"""Return cross product.
Parameters
----------
a : numpy.ndarray
3-dimensional vector.
b : numpy.ndarray
3-dimensional vector.
Returns
-------
cross_prod : numpy.ndarray
calculated cross product
"""
return np.dot(outer_product_matrix(a), b)
def quaternion2rpy(q):
"""Returns Roll-pitch-yaw angles of a given quaternion.
Parameters
----------
q : numpy.ndarray or list
Quaternion in [w x y z] format.
Returns