/
base.py
1620 lines (1404 loc) · 55.1 KB
/
base.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
import copy
import sys
import warnings
import numpy as np
from skrobot.coordinates.dual_quaternion import DualQuaternion
from skrobot.coordinates.math import _check_valid_rotation
from skrobot.coordinates.math import _check_valid_translation
from skrobot.coordinates.math import angle_between_vectors
from skrobot.coordinates.math import convert_to_axis_vector
from skrobot.coordinates.math import cross_product
from skrobot.coordinates.math import matrix2quaternion
from skrobot.coordinates.math import matrix_log
from skrobot.coordinates.math import normalize_vector
from skrobot.coordinates.math import quaternion2matrix
from skrobot.coordinates.math import quaternion_multiply
from skrobot.coordinates.math import random_rotation
from skrobot.coordinates.math import random_translation
from skrobot.coordinates.math import rotate_matrix
from skrobot.coordinates.math import rotation_angle
from skrobot.coordinates.math import rotation_matrix
from skrobot.coordinates.math import rpy2quaternion
from skrobot.coordinates.math import rpy_angle
def transform_coords(c1, c2, out=None):
"""Return Coordinates by applying c1 to c2 from the left
Parameters
----------
c1 : skrobot.coordinates.Coordinates
c2 : skrobot.coordinates.Coordinates
Coordinates
c3 : skrobot.coordinates.Coordinates or None
Output argument. If this value is specified, the results will be
in-placed.
Returns
-------
Coordinates(pos=translation, rot=q) : skrobot.coordinates.Coordinates
new coordinates
Examples
--------
>>> from skrobot.coordinates import Coordinates
>>> from skrobot.coordinates import transform_coords
>>> from numpy import pi
>>> c1 = Coordinates()
>>> c2 = Coordinates()
>>> c3 = transform_coords(c1, c2)
>>> c3.translation
array([0., 0., 0.])
>>> c3.rotation
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> c1 = Coordinates().translate([0.1, 0.2, 0.3]).rotate(pi / 3.0, 'x')
>>> c2 = Coordinates().translate([0.3, -0.3, 0.1]).rotate(pi / 2.0, 'y')
>>> c3 = transform_coords(c1, c2)
>>> c3.translation
array([ 0.4 , -0.03660254, 0.09019238])
>>> c3.rotation
>>> c3.rotation
array([[ 1.94289029e-16, 0.00000000e+00, 1.00000000e+00],
[ 8.66025404e-01, 5.00000000e-01, -1.66533454e-16],
[-5.00000000e-01, 8.66025404e-01, 2.77555756e-17]])
"""
if out is None:
out = Coordinates(check_validity=False)
elif not isinstance(out, Coordinates):
raise TypeError("Input type should be skrobot.coordinates.Coordinates")
out._translation = c1._translation + np.dot(c1._rotation, c2._translation)
out._rotation = np.matmul(c1._rotation, c2._rotation)
return out
class Transform(object):
"""Transform specified by translation and rotation
Parameters
----------
translation : list(3,) or numpy.ndarray(3,)
translation
rot : numpy.ndarray(3, 3)
3x3 rotation matrix
"""
def __init__(self, translation, rotation):
self.translation = np.array(translation)
self.rotation = rotation
def transform_vector(self, vec):
"""Apply this transform to vector/vectors
Parameters
----------
vec : numpy.ndarray(3,) or numpy.ndarray(n_points, 3)
vector/vectors to be transformed
Returns
-------
vec_transformed : numpy.ndarray(3,) or numpy.ndarray(n_points, 3)
transformed points
"""
assert vec.ndim < 3, "vec must be either 1 or 2 dimensional."
if vec.ndim == 1:
return self.rotation.dot(vec.T) + self.translation
if vec.ndim == 2:
return self.rotation.dot(vec.T).T + self.translation[None, :]
def rotate_vector(self, vec):
"""Rotate 3-dimensional vector using rotation of this Transform
Parameters
----------
vec : numpy.ndarray(3,) or numpy.ndarray(3, n_points)
vector (or vectors) to be roated
Returns
-------
vec_transformed : numpy.ndarray(3,), numpy.ndarray(3, n_points)
rotated vector (or vectors)
"""
assert vec.ndim < 3, "vec must be either 1 or 2 dimensional."
if vec.ndim == 1:
return self.rotation.dot(vec.T)
if vec.ndim == 2:
return self.rotation.dot(vec.T).T
def inverse_transformation(self):
"""Return inverse transform
Returns
-------
inv_transform : skrobot.coordinates.base.Transform
inverse transformation
"""
new_rot = self.rotation.T
new_trans = -new_rot.dot(self.translation)
return Transform(new_trans, new_rot)
def __mul__(self, tf_23):
"""Composite this transform with other transform
Parameters
----------
tf_23 : skrobot.coordinates.base.Transform
the other transform.
Returns
-------
tf_13 : skrobot.coordinates.base.Transform
Let this (self) transform as tf_12, then with the
other transform tf_23, we obtain tf_13 = tf_12 * tf_23
"""
tf_12 = self
tran_12, rot_12 = tf_12.translation, tf_12.rotation
tran_23, rot_23 = tf_23.translation, tf_23.rotation
rot_13 = rot_23.dot(rot_12)
tran_13 = tran_23 + rot_23.dot(tran_12)
tf_13 = Transform(tran_13, rot_13)
return tf_13
def __rmul__(self, other):
return other.__mul__(self)
class Coordinates(object):
"""Coordinates class to manipulate rotation and translation.
Parameters
----------
pos : list or numpy.ndarray or None
shape of (3,) translation vector. or
4x4 homogeneous transformation matrix.
If the homogeneous transformation matrix is given,
`rot` will be overwritten.
If this value is `None`, set [0, 0, 0] vector as default.
rot : list or numpy.ndarray or None
we can take 3x3 rotation matrix or
[yaw, pitch, roll] or
quaternion [w, x, y, z] order
If this value is `None`, set the identity matrix as default.
name : str or None
name of this coordinates
check_validity : bool (optional)
Default `True`.
If this value is `True`, check whether an input rotation
and an input translation are valid.
"""
def __init__(self,
pos=None,
rot=None,
name=None,
hook=None,
check_validity=True):
if check_validity:
if (isinstance(pos, list) or isinstance(pos, np.ndarray)):
T = np.array(pos, dtype=np.float64)
if T.shape == (4, 4):
pos = T[:3, 3]
rot = T[:3, :3]
if rot is None:
self._rotation = np.eye(3)
else:
self.rotation = rot
if pos is None:
self._translation = np.array([0, 0, 0])
else:
self.translation = pos
else:
if rot is None:
self._rotation = np.eye(3)
else:
self._rotation = rot
if pos is None:
self._translation = np.array([0, 0, 0])
else:
self._translation = pos
if name is None:
name = ''
self.name = name
self.parent = None
self._hook = hook
def disable_hook(self):
if self._hook is not None:
original_hook = self._hook
self._hook = None
return True, original_hook
return False, None
def get_transform(self):
"""Return Transform object
Returns
-------
transform : skrobot.coordinates.base.Transform
corrensponding Transform to this coordinates
"""
return Transform(self.worldpos(), self.worldrot())
@property
def rotation(self):
"""Return rotation matrix of this coordinates.
Returns
-------
self._rotation : numpy.ndarray
3x3 rotation matrix
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates import Coordinates
>>> c = Coordinates()
>>> c.rotation
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> c.rotate(np.pi / 2.0, 'y')
>>> c.rotation
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 self._hook is not None:
self._hook()
return self._rotation
@rotation.setter
def rotation(self, rotation):
"""Set rotation of this coordinate
This setter checkes the given rotation and set it this coordinate.
Parameters
----------
rotation : list or numpy.ndarray
we can take 3x3 rotation matrix or
rpy angle [yaw, pitch, roll] or
quaternion [w, x, y, z] order
"""
rotation = np.array(rotation)
# Convert quaternions
if rotation.shape == (4,):
q = np.array([q for q in rotation])
if np.abs(np.linalg.norm(q) - 1.0) > 1e-3:
raise ValueError('Invalid quaternion. Must be '
'norm 1.0, get {}'.
format(np.linalg.norm(q)))
rotation = quaternion2matrix(q)
elif rotation.shape == (3,):
# Convert [yaw-pitch-roll] to rotation matrix
q = rpy2quaternion(rotation)
rotation = quaternion2matrix(q)
# Convert lists and tuples
if type(rotation) in (list, tuple):
rotation = np.array(rotation).astype(np.float32)
_check_valid_rotation(rotation)
self._rotation = rotation * 1.
@property
def translation(self):
"""Return translation of this coordinates.
Returns
-------
self._translation : numpy.ndarray
vector shape of (3, ). unit is [m]
Examples
--------
>>> from skrobot.coordinates import Coordinates
>>> c = Coordinates()
>>> c.translation
array([0., 0., 0.])
>>> c.translate([0.1, 0.2, 0.3])
>>> c.translation
array([0.1, 0.2, 0.3])
"""
if self._hook is not None:
self._hook()
return self._translation
@translation.setter
def translation(self, translation):
"""Set translation of this coordinate
This setter checkes the given translation and set it this coordinate.
Parameters
----------
translation : list or tuple or numpy.ndarray
shape of (3,) translation vector
"""
# Convert lists to translation arrays
if type(translation) in (list, tuple) and len(translation) == 3:
translation = np.array([t for t in translation]).astype(np.float64)
_check_valid_translation(translation)
self._translation = translation.squeeze() * 1.
@property
def name(self):
"""Return this coordinate's name
Returns
-------
self._name : str
name of this coordinate
"""
return self._name
@name.setter
def name(self, name):
"""Setter of this coordinate's name
Parameters
----------
name : str
name of this coordinate
"""
if not isinstance(name, str):
raise TypeError('name should be string, get {}'.
format(type(name)))
self._name = name
@property
def dimension(self):
"""Return dimension of this coordinate
Returns
-------
len(self.translation) : int
dimension of this coordinate
"""
return len(self._translation)
@property
def x_axis(self):
"""Return x axis vector of this coordinates.
Returns
-------
axis : numpy.ndarray
x axis.
"""
return np.array(self._rotation[:, 0].T, 'f')
@property
def y_axis(self):
"""Return y axis vector of this coordinates.
Returns
-------
axis : numpy.ndarray
y axis.
"""
return np.array(self._rotation[:, 1].T, 'f')
@property
def z_axis(self):
"""Return z axis vector of this coordinates.
Returns
-------
axis : numpy.ndarray
z axis.
"""
return np.array(self._rotation[:, 2].T, 'f')
def changed(self):
"""Return False
This is used for CascadedCoords compatibility
Returns
-------
False : bool
always return False
"""
return False
def translate(self, vec, wrt='local'):
"""Translate this coordinates.
Note that this function changes this coordinates self.
So if you don't want to change this class, use copy_worldcoords()
Parameters
----------
vec : list or numpy.ndarray
shape of (3,) translation vector. unit is [m] order.
wrt : str or Coordinates (optional)
translate with respect to wrt.
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates import Coordinates
>>> c = Coordinates()
>>> c.translation
array([0., 0., 0.], dtype=float32)
>>> c.translate([0.1, 0.2, 0.3])
>>> c.translation
array([0.1, 0.2, 0.3], dtype=float32)
>>> c = Coordinates()
>>> c.copy_worldcoords().translate([0.1, 0.2, 0.3])
>>> c.translation
array([0., 0., 0.], dtype=float32)
>>> c = Coordinates().rotate(np.pi / 2.0, 'y')
>>> c.translate([0.1, 0.2, 0.3])
>>> c.translation
array([ 0.3, 0.2, -0.1])
>>> c = Coordinates().rotate(np.pi / 2.0, 'y')
>>> c.translate([0.1, 0.2, 0.3], 'world')
>>> c.translation
array([0.1, 0.2, 0.3])
"""
vec = np.array(vec, dtype=np.float64)
return self.newcoords(
self._rotation,
self.parent_orientation(vec, wrt) + self._translation,
check_validity=False)
def transform_vector(self, v):
""""Return vector represented at world frame.
Vector v given in the local coords is converted to world
representation.
Parameters
----------
v : numpy.ndarray
3d vector.
We can take batch of vector like (batch_size, 3)
Returns
-------
transformed_point : numpy.ndarray
transformed point
"""
v = np.array(v, dtype=np.float64)
if v.ndim == 2:
return (np.matmul(self._rotation, v.T)
+ self._translation.reshape(3, -1)).T
return np.matmul(self._rotation, v) + self._translation
def inverse_transform_vector(self, vec):
"""Transform vector in world coordinates to local coordinates
Parameters
----------
vec : numpy.ndarray
3d vector.
We can take batch of vector like (batch_size, 3)
Returns
-------
transformed_point : numpy.ndarray
transformed point
"""
vec = np.array(vec, dtype=np.float64)
if vec.ndim == 2:
return (np.matmul(self._rotation.T, vec.T)
- np.matmul(
self._rotation.T, self._translation).reshape(3, -1)).T
return np.matmul(self._rotation.T, vec) - \
np.matmul(self._rotation.T, self._translation)
def inverse_transformation(self, dest=None):
"""Return a invese transformation of this coordinate system.
Create a new coordinate with inverse transformation of this
coordinate system.
.. math::
\\left(
\\begin{array}{ccc}
R^{-1} & - R^{-1} p \\\\
0 & 1
\\end{array}
\\right)
Parameters
----------
dest : None or skrobot.coordinates.Coordinates
If dest is given, the result of transformation
is in-placed to dest.
Returns
-------
dest : skrobot.coordinates.Coordinates
result of inverse transformation.
"""
if dest is None:
dest = Coordinates(check_validity=False)
dest._rotation = self._rotation.T
dest._translation = np.matmul(dest._rotation, self._translation)
dest._translation = -1.0 * dest._translation
return dest
def transformation(self, c2, wrt='local'):
c2 = c2.worldcoords()
c1 = self.worldcoords()
inv = c1.inverse_transformation()
if wrt == 'local' or wrt == self:
transform_coords(inv, c2, inv)
elif wrt == 'parent' or \
wrt == self.parent or \
wrt == 'world':
transform_coords(c2, inv, inv)
elif isinstance(wrt, Coordinates):
xw = wrt.worldcoords()
transform_coords(c2, inv, inv)
transform_coords(xw.inverse_transformation(), inv, inv)
transform_coords(inv, xw, inv)
else:
raise ValueError('wrt {} not supported'.format(wrt))
return inv
def T(self):
"""Return 4x4 homogeneous transformation matrix.
Returns
-------
matrix : numpy.ndarray
homogeneous transformation matrix shape of (4, 4)
Examples
--------
>>> from numpy import pi
>>> from skrobot.coordinates import make_coords
>>> c = make_coords()
>>> c.T()
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
>>> c.translate([0.1, 0.2, 0.3])
>>> c.rotate(pi / 2.0, 'y')
array([[ 2.22044605e-16, 0.00000000e+00, 1.00000000e+00,
1.00000000e-01],
[ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00,
2.00000000e-01],
[-1.00000000e+00, 0.00000000e+00, 2.22044605e-16,
3.00000000e-01],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00]])
"""
matrix = np.zeros((4, 4), dtype=np.float64)
matrix[3, 3] = 1.0
matrix[:3, :3] = self._rotation
matrix[:3, 3] = self._translation
return matrix
@property
def quaternion(self):
"""Property of quaternion
Returns
-------
q : numpy.ndarray
[w, x, y, z] quaternion
Examples
--------
>>> from numpy import pi
>>> from skrobot.coordinates import make_coords
>>> c = make_coords()
>>> c.quaternion
array([1., 0., 0., 0.])
>>> c.rotate(pi / 3, 'y').rotate(pi / 5, 'z')
>>> c.quaternion
array([0.8236391 , 0.1545085 , 0.47552826, 0.26761657])
"""
return matrix2quaternion(self._rotation)
@property
def dual_quaternion(self):
"""Property of DualQuaternion
Return DualQuaternion representation of this coordinate.
Returns
-------
DualQuaternion : skrobot.coordinates.dual_quaternion.DualQuaternion
DualQuaternion representation of this coordinate
"""
qr = normalize_vector(self.quaternion)
x, y, z = self._translation
qd = quaternion_multiply(np.array([0, x, y, z]), qr) * 0.5
return DualQuaternion(qr, qd)
def parent_orientation(self, v, wrt):
if wrt == 'local' or wrt == self:
return np.matmul(self._rotation, v)
if wrt == 'parent' \
or wrt == self.parent \
or wrt == 'world':
return v
if coordinates_p(wrt):
return np.matmul(wrt.worldrot(), v)
raise ValueError('wrt {} not supported'.format(wrt))
def rotate_vector(self, v):
"""Rotate 3-dimensional vector using rotation of this coordinate
Parameters
----------
v : numpy.ndarray
vector shape of (3,)
Returns
-------
np.matmul(self._rotation, v) : numpy.ndarray
rotated vector
Examples
--------
>>> from skrobot.coordinates import Coordinates
>>> from numpy import pi
>>> c = Coordinates().rotate(pi, 'z')
>>> c.rotate_vector([1, 2, 3])
array([-1., -2., 3.])
"""
return np.matmul(self._rotation, v)
def inverse_rotate_vector(self, v):
return np.matmul(v, self._rotation)
def transform(self, c, wrt='local', out=None):
"""Transform this coordinates by coords based on wrt
Note that this function changes this coordinates
translation and rotation.
If you would like not to change this coordinates,
Please use copy_worldcoords() or give `out`.
Parameters
----------
c : skrobot.coordinates.Coordinates
coordinate
wrt : str or skrobot.coordinates.Coordinates
If wrt is 'local' or self, multiply c from the right.
If wrt is 'world' or 'parent' or self.parent,
transform c with respect to worldcoord.
If wrt is Coordinates, transform c with respect to c.
out : None or skrobot.coordinates.Coordinates
If the `out` is specified, set new coordinates to `out`.
Note that if the `out` is given, these coordinates don't change.
Returns
-------
self : skrobot.coordinates.Coordinates
return this coordinate
Examples
--------
"""
if out is None:
out = self
if wrt == 'local' or wrt == self:
# multiply c from the right
transform_coords(self, c, out)
elif wrt == 'parent' or wrt == self.parent \
or wrt == 'world':
# multiply c from the left
transform_coords(c, self, out)
elif isinstance(wrt, Coordinates):
transform_coords(wrt.inverse_transformation(), self, out)
transform_coords(c, out, out)
transform_coords(wrt.worldcoords(), out, out)
else:
raise ValueError('transform wrt {} is not supported'.format(wrt))
return out
def move_coords(self, target_coords, local_coords):
"""Transform this coordinate so that local_coords to target_coords.
Parameters
----------
target_coords : skrobot.coordinates.Coordinates
target coords.
local_coords : skrobot.coordinates.Coordinates
local coords to be aligned.
Returns
-------
self.worldcoords() : skrobot.coordinates.Coordinates
world coordinates.
"""
self.transform(
local_coords.transformation(target_coords), local_coords)
return self.worldcoords()
def rpy_angle(self):
"""Return a pair of rpy angles of this coordinates.
Returns
-------
rpy_angle(self._rotation) : tuple(numpy.ndarray, numpy.ndarray)
a pair of rpy angles. See also skrobot.coordinates.math.rpy_angle
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates import Coordinates
>>> c = Coordinates().rotate(np.pi / 2.0, 'x').rotate(np.pi / 3.0, 'z')
>>> r.rpy_angle()
(array([ 3.84592537e-16, -1.04719755e+00, 1.57079633e+00]),
array([ 3.14159265, -2.0943951 , -1.57079633]))
"""
return rpy_angle(self._rotation)
def axis(self, ax):
ax = convert_to_axis_vector(ax)
return self.rotate_vector(ax)
def difference_position(self, coords,
translation_axis=True):
"""Return differences in positoin of given coords.
Parameters
----------
coords : skrobot.coordinates.Coordinates
given coordinates
translation_axis : str or bool or None (optional)
we can take 'x', 'y', 'z', 'xy', 'yz', 'zx', 'xx', 'yy', 'zz',
True or False(None).
Returns
-------
dif_pos : numpy.ndarray
difference position of self coordinates and coords
considering translation_axis.
Examples
--------
>>> from skrobot.coordinates import Coordinates
>>> from skrobot.coordinates import transform_coords
>>> from numpy import pi
>>> c1 = Coordinates().translate([0.1, 0.2, 0.3]).rotate(
... pi / 3.0, 'x')
>>> c2 = Coordinates().translate([0.3, -0.3, 0.1]).rotate(
... pi / 2.0, 'y')
>>> c1.difference_position(c2)
array([ 0.2 , -0.42320508, 0.3330127 ])
>>> c1 = Coordinates().translate([0.1, 0.2, 0.3]).rotate(0, 'x')
>>> c2 = Coordinates().translate([0.3, -0.3, 0.1]).rotate(
... pi / 3.0, 'x')
>>> c1.difference_position(c2)
array([ 0.2, -0.5, -0.2])
"""
dif_pos = self.inverse_transform_vector(coords.worldpos())
translation_axis = convert_to_axis_vector(translation_axis)
dif_pos[translation_axis == 1] = 0.0
return dif_pos
def difference_rotation(self, coords,
rotation_axis=True):
"""Return differences in rotation of given coords.
Parameters
----------
coords : skrobot.coordinates.Coordinates
given coordinates
rotation_axis : str or bool or None (optional)
we can take 'x', 'y', 'z', 'xx', 'yy', 'zz', 'xm', 'ym', 'zm',
'xy', 'yx', 'yz', 'zy', 'zx', 'xz', True or False(None).
Returns
-------
dif_rot : numpy.ndarray
difference rotation of self coordinates and coords
considering rotation_axis.
Examples
--------
>>> from numpy import pi
>>> from skrobot.coordinates import Coordinates
>>> from skrobot.coordinates.math import rpy_matrix
>>> coord1 = Coordinates()
>>> coord2 = Coordinates(rot=rpy_matrix(pi / 2.0, pi / 3.0, pi / 5.0))
>>> coord1.difference_rotation(coord2)
array([-0.32855112, 1.17434985, 1.05738936])
>>> coord1.difference_rotation(coord2, rotation_axis=False)
array([0, 0, 0])
>>> coord1.difference_rotation(coord2, rotation_axis='x')
array([0. , 1.36034952, 0.78539816])
>>> coord1.difference_rotation(coord2, rotation_axis='y')
array([0.35398131, 0. , 0.97442695])
>>> coord1.difference_rotation(coord2, rotation_axis='z')
array([-0.88435715, 0.74192175, 0. ])
Using mirror option ['xm', 'ym', 'zm'], you can
allow differences of mirror direction.
>>> coord1 = Coordinates()
>>> coord2 = Coordinates().rotate(pi, 'x')
>>> coord1.difference_rotation(coord2, 'xm')
array([-2.99951957e-32, 0.00000000e+00, 0.00000000e+00])
>>> coord1 = Coordinates()
>>> coord2 = Coordinates().rotate(pi / 2.0, 'x')
>>> coord1.difference_rotation(coord2, 'xm')
array([-1.57079633, 0. , 0. ])
"""
def need_mirror_for_nearest_axis(coords0, coords1, ax):
a0 = coords0.axis(ax)
a1 = coords1.axis(ax)
a1_mirror = - a1
dr1 = angle_between_vectors(a0, a1, normalize=False) \
* normalize_vector(cross_product(a0, a1))
dr1m = angle_between_vectors(a0, a1_mirror, normalize=False) \
* normalize_vector(cross_product(a0, a1_mirror))
return np.linalg.norm(dr1) < np.linalg.norm(dr1m)
if rotation_axis in ['x', 'y', 'z']:
a0 = self.axis(rotation_axis)
a1 = coords.axis(rotation_axis)
if np.abs(np.linalg.norm(np.array(a0) - np.array(a1))) < 0.001:
dif_rot = np.array([0, 0, 0], 'f')
else:
dif_rot = np.matmul(
self.worldrot().T,
angle_between_vectors(a0, a1, normalize=False)
* normalize_vector(cross_product(a0, a1)))
elif rotation_axis in ['xx', 'yy', 'zz']:
ax = rotation_axis[0]
a0 = self.axis(ax)
a2 = coords.axis(ax)
if not need_mirror_for_nearest_axis(self, coords, ax):
a2 = - a2
dif_rot = np.matmul(
self.worldrot().T,
angle_between_vectors(a0, a2, normalize=False)
* normalize_vector(cross_product(a0, a2)))
elif rotation_axis in ['xy', 'yx', 'yz', 'zy', 'zx', 'xz']:
if rotation_axis in ['xy', 'yx']:
ax1 = 'z'
ax2 = 'x'
elif rotation_axis in ['yz', 'zy']:
ax1 = 'x'
ax2 = 'y'
else:
ax1 = 'y'
ax2 = 'z'
a0 = self.axis(ax1)
a1 = coords.axis(ax1)
dif_rot = np.matmul(
self.worldrot().T,
angle_between_vectors(a0, a1, normalize=False)
* normalize_vector(cross_product(a0, a1)))
norm = np.linalg.norm(dif_rot)
if np.isclose(norm, 0.0):
self_coords = self.copy_worldcoords()
else:
self_coords = self.copy_worldcoords().rotate(norm, dif_rot)
a0 = self_coords.axis(ax2)
a1 = coords.axis(ax2)
dif_rot = np.matmul(
self_coords.worldrot().T,
angle_between_vectors(a0, a1, normalize=False)
* normalize_vector(cross_product(a0, a1)))
elif rotation_axis in ['xm', 'ym', 'zm']:
rot = coords.worldrot()
ax = rotation_axis[0]
if not need_mirror_for_nearest_axis(self, coords, ax):
rot = rotate_matrix(rot, np.pi, ax)
dif_rot = matrix_log(np.matmul(self.worldrot().T, rot))
elif rotation_axis is False or rotation_axis is None:
dif_rot = np.array([0, 0, 0])
elif rotation_axis is True:
dif_rotmatrix = np.matmul(self.worldrot().T,
coords.worldrot())
dif_rot = matrix_log(dif_rotmatrix)
else:
raise ValueError
return dif_rot
def rotate_with_matrix(self, mat, wrt='local'):
"""Rotate this coordinate by given rotation matrix.
This is a subroutine of self.rotate function.
Parameters
----------
mat : numpy.ndarray
rotation matrix shape of (3, 3)
wrt : str or skrobot.coordinates.Coordinates
with respect to.
Returns
-------
self : skrobot.coordinates.Coordinates
"""
if wrt == 'local' or wrt == self:
rot = np.matmul(self._rotation, mat)
self.newcoords(rot, self._translation, check_validity=False)
elif wrt == 'parent' or wrt == self.parent or \
wrt == 'world' or wrt is None or \
wrt == worldcoords:
rot = np.matmul(mat, self._rotation)
self.newcoords(rot, self._translation, check_validity=False)
elif isinstance(wrt, Coordinates):
r2 = wrt.worldrot()
r2t = r2.T
r2t = np.matmul(mat, r2t)
r2t = np.matmul(r2, r2t)
self._rotation = np.matmul(r2t, self._rotation)
else:
raise ValueError('wrt {} is not supported'.format(wrt))
return self
def rotate(self, theta, axis=None, wrt='local', skip_normalization=False):
"""Rotate this coordinate by given theta and axis.
This coordinate system is rotated relative to theta radians
around the `axis` axis.
Note that this function does not change a position of this coordinate.
If you want to rotate this coordinates around with world frame,
you can use `transform` function.
Please see examples.
Parameters
----------
theta : float
relartive rotation angle in radian.
axis : str or None or numpy.ndarray
axis of rotation.
The value of `axis` is represented as `wrt` frame.
wrt : str or skrobot.coordinates.Coordinates
skip_normalization : bool
if `True`, skip normalization for axis.
Returns
-------
self : skrobot.coordinates.Coordinates
Examples
--------
>>> from skrobot.coordinates import Coordinates
>>> from numpy import pi
>>> c = Coordinates()
>>> c.translate((1.0, 0, 0))
>>> c.rotate(pi / 2.0, 'z', wrt='local')
>>> c.translation
array([1., 0., 0.])
>>> c.transform(Coordinates().rotate(np.pi / 2.0, 'z'), wrt='world')
>>> c.translation
array([0., 1., 0.])
"""
if isinstance(axis, list) or isinstance(axis, np.ndarray):