-
Notifications
You must be signed in to change notification settings - Fork 12
/
models.py
1353 lines (1064 loc) · 45.1 KB
/
models.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 os
import warnings
import functools
import casadi as cs
# https://wiki.ros.org/xacro
import xacro
# https://pypi.org/project/urdf-parser-py
from urdf_parser_py.urdf import URDF, Joint, Link, Pose
from .spatialmath import *
def listify_output(fun):
@functools.wraps(fun)
def listify(*args, **kwargs):
args = list(args) # makes concatenation easier later
# Handle cases where a list is required
output = None
if len(args) > 1:
q = args[2] # joint states are always given at index 2
# Check if q is a trajectory
if q.shape[1] > 1:
# Convert output to list
output = []
for i in range(q.shape[1]):
args_ = [args[0], args[1], q[:, i]] + args[3:]
output.append(fun(*args_, **kwargs))
# Merge list when elements are vectors
if output[0].shape[1] == 1:
output = cs.horzcat(*output)
# When list wasn't required (i.e. output is still None), just evaluate function
if output is None:
output = fun(*args, **kwargs)
return output
return listify
def deprecation_warning(name_to):
def decorator(function):
def wrapper(*args, **kwargs):
name_from = function.__name__
warn = f"'{name_from}' will be deprecated, please use '{name_to}' instead"
msg = "\033[93m" + warn + "\033[0m" # add
warnings.warn(msg, DeprecationWarning, stacklevel=2)
self_ = args[0]
new_function = getattr(self_, name_to)
while hasattr(new_function, "__wrapped__"):
new_function = new_function.__wrapped__
args_use = list(args)
if function.__name__.endswith("_function"):
args_use = args_use[1:]
return new_function(*args_use, **kwargs)
return wrapper
return decorator
class Model:
"""
Model base class
"""
def __init__(self, name, dim, time_derivs, symbol, dlim, T):
"""
name (str):
Name of model.
dim (int):
Model dimension (for robots this is ndof).
time_derivs (list[int]):
Time derivatives required for model, 0 means not time derivative, 1 means first derivative wrt to time is required, etc.
symbol (str):
A short symbol to represent the model state.
dlim (dict[ int, tuple[list[float]] ]):
limits on each time derivative, index should correspond to a time derivative (i.e. 0, 1, ...) and the value should be a tuple of two lists containing the lower and upper bounds .
T (int)
Optionally use this to override the number of time-steps given in the OptimizationBuilder constructor.
"""
self.name = name
self.dim = dim
self.time_derivs = time_derivs
self.symbol = symbol
self.dlim = dlim
self.T = T
def get_name(self):
"""Return the name of the model."""
return self.name
def state_name(self, time_deriv):
"""Return the state name.
Syntax
------
state_name = model.state_name(time_deriv)
Parameters
----------
time_deriv (int)
The time-deriviative required (i.e. position is 0, velocity is 1, etc.)
Returns
-------
state_name (string)
The state name in the form {name}/{d}{symbol}, where "name" is the model name, d is a string given by 'd'*time_deriv, and symbol is the symbol for the model state.
"""
assert (
time_deriv in self.time_derivs
), f"Given time derivative {time_deriv=} is not recognized, only allowed {self.time_derivs}"
return self.name + "/" + "d" * time_deriv + self.symbol
def state_parameter_name(self, time_deriv):
"""Return the parameter name.
Syntax
------
state_parameter_name = model.state_parameter_name(time_deriv)
Parameters
----------
time_deriv (int)
The time-deriviative required (i.e. position is 0, velocity is 1, etc.)
Returns
-------
state_parameter_name (string)
The parameter name in the form {name}/{d}{symbol}/p, where "name" is the model name, d is a string given by 'd'*time_deriv, and symbol is the symbol for the model parameters.
"""
assert (
time_deriv in self.time_derivs
), f"Given time derivative {time_deriv=} is not recognized, only allowed {self.time_derivs}"
return self.name + "/" + "d" * time_deriv + self.symbol + "/" + "p"
def state_optimized_name(self, time_deriv):
"""Return the parameter name.
Syntax
------
state_optimized_name = model.state_optimized_name(time_deriv)
Parameters
----------
time_deriv (int)
The time-deriviative required (i.e. position is 0, velocity is 1, etc.)
Returns
-------
state_optimized_name (string)
The parameter name in the form {name}/{d}{symbol_param}/x, where "name" is the model name, d is a string given by 'd'*time_deriv, and symbol_param is the symbol for the model parameters.
"""
assert (
time_deriv in self.time_derivs
), f"Given time derivative {time_deriv=} is not recognized, only allowed {self.time_derivs}"
return self.name + "/" + "d" * time_deriv + self.symbol + "/" + "x"
def get_limits(self, time_deriv):
"""Return the model limits.
Syntax
------
lower, upper = model.get_limits(time_deriv)
Parameters
----------
time_deriv (int)
The time-deriviative required (i.e. position is 0, velocity is 1, etc.)
Returns
-------
lower/upper (casadi.DM)
The model lower/upper limits.
"""
assert (
time_deriv in self.time_derivs
), f"Given time derivative {time_deriv=} is not recognized, only allowed {self.time_derivs}"
assert (
time_deriv in self.dlim.keys()
), f"Limit for time derivative {time_deriv=} has not been given"
return self.dlim[time_deriv]
def in_limit(self, x, time_deriv):
"""True when x is within limits for a given time derivative, False otherwise. The return type uses CasADi, so this can be used in the formulation."""
lo, up = self.get_limits(time_deriv)
return cs.logic_all(cs.logical_and(lo <= x, x <= up))
class TaskModel(Model):
def __init__(
self,
name,
dim,
time_derivs=[0],
symbol="y",
dlim={},
T=None,
):
super().__init__(name, dim, time_derivs, symbol, dlim, T)
class JointTypeNotSupported(NotImplementedError):
def __init__(self, joint_type):
msg = f"{joint_type} joints are currently not supported\n"
msg += "if you require this joint type please raise an issue at "
msg += "https://github.com/cmower/optas/issues"
super().__init__(msg)
class RobotModel(Model):
def __init__(
self,
urdf_filename=None,
urdf_string=None,
xacro_filename=None,
name=None,
time_derivs=[0],
qddlim=None,
T=None,
param_joints=[],
):
# If xacro is passed then convert to urdf string
self._xacro_filename = xacro_filename
if xacro_filename is not None:
try:
urdf_string = xacro.process(xacro_filename)
except AttributeError:
from io import StringIO
xml = xacro.process_file(xacro_filename)
str_io = StringIO()
xml.writexml(str_io)
urdf_string = str_io.getvalue()
# Load URDF
self._urdf = None
self._urdf_filename = None
self._urdf_string = None
if urdf_filename is not None:
self._urdf_filename = urdf_filename
self._urdf = URDF.from_xml_file(urdf_filename)
if urdf_string is not None:
self._urdf = URDF.from_xml_string(urdf_string)
assert (
self._urdf is not None
), "You need to supply a urdf, either through filename or as a string"
# Setup joint limits, joint position/velocity limits
self.param_joints = param_joints
dlim = {
0: (self.lower_optimized_joint_limits, self.upper_optimized_joint_limits),
1: (
-self.velocity_optimized_joint_limits,
self.velocity_optimized_joint_limits,
),
}
# Handle potential acceleration limit
if qddlim:
qddlim = vec(qddlim)
if qddlim.shape[0] == 1:
qddlim = qddlim * cs.DM.ones(self.ndof)
assert (
qddlim.shape[0] == self.ndof
), f"expected ddlim to have {self.ndof} elements"
dlim[2] = -qddlim, qddlim
# If user did not supply name for the model then use the one in the URDF
if name is None:
name = self._urdf.name
super().__init__(name, self.ndof, time_derivs, "q", dlim, T)
def get_urdf(self):
return self._urdf
def get_urdf_dirname(self):
if self._urdf_filename is not None:
return os.path.dirname(self._urdf_filename)
elif self._xacro_filename is not None:
return os.path.dirname(self._xacro_filename)
@property
def joint_names(self):
return [jnt.name for jnt in self._urdf.joints]
@property
def link_names(self):
return [lnk.name for lnk in self._urdf.links]
@property
def actuated_joint_names(self):
return [jnt.name for jnt in self._urdf.joints if jnt.type != "fixed"]
@property
def parameter_joint_names(self):
return [
joint for joint in self.actuated_joint_names if joint in self.param_joints
]
@property
def parameter_joint_indexes(self):
return [
self._get_actuated_joint_index(joint)
for joint in self.parameter_joint_names
]
@property
def optimized_joint_names(self):
return [
joint
for joint in self.actuated_joint_names
if joint not in self.parameter_joint_names
]
@property
def optimized_joint_indexes(self):
return [
self._get_actuated_joint_index(joint)
for joint in self.optimized_joint_names
]
@property
def parameter_joint_names(self):
return [
joint for joint in self.actuated_joint_names if joint in self.param_joints
]
@property
def parameter_joint_indexes(self):
return [
self._get_actuated_joint_index(joint)
for joint in self.parameter_joint_names
]
@property
def optimized_joint_names(self):
return [
joint
for joint in self.actuated_joint_names
if joint not in self.parameter_joint_names
]
@property
def optimized_joint_indexes(self):
return [
self._get_actuated_joint_index(joint)
for joint in self.optimized_joint_names
]
@property
def parameter_joint_names(self):
return [
joint for joint in self.actuated_joint_names if joint in self.param_joints
]
@property
def parameter_joint_indexes(self):
return [
self._get_actuated_joint_index(joint)
for joint in self.parameter_joint_names
]
def extract_parameter_dimensions(self, values):
return values[self.parameter_joint_indexes, :]
@property
def optimized_joint_names(self):
return [
joint
for joint in self.actuated_joint_names
if joint not in self.parameter_joint_names
]
@property
def optimized_joint_indexes(self):
return [
self._get_actuated_joint_index(joint)
for joint in self.optimized_joint_names
]
def extract_optimized_dimensions(self, values):
return values[self.optimized_joint_indexes, :]
@property
def ndof(self):
"""Number of degrees of freedom."""
return len(self.actuated_joint_names)
@property
def num_opt_joints(self):
"""Number of optimized joints"""
return len(self.optimized_joint_names)
@property
def num_param_joints(self):
"""Number of joints defined as parameter"""
return len(self.parameter_joint_names)
def get_joint_lower_limit(self, joint):
if joint.limit is None:
return -1e9
return joint.limit.lower
def get_joint_upper_limit(self, joint):
if joint.limit is None:
return 1e9
return joint.limit.upper
def get_velocity_joint_limit(self, joint):
if joint.limit is None:
return 1e9
return joint.limit.velocity
@property
def lower_actuated_joint_limits(self):
return cs.DM(
[
self.get_joint_lower_limit(jnt)
for jnt in self._urdf.joints
if jnt.type != "fixed"
]
)
@property
def upper_actuated_joint_limits(self):
return cs.DM(
[
self.get_joint_upper_limit(jnt)
for jnt in self._urdf.joints
if jnt.type != "fixed"
]
)
@property
def velocity_actuated_joint_limits(self):
return cs.DM(
[
self.get_velocity_joint_limit(jnt)
for jnt in self._urdf.joints
if jnt.type != "fixed"
]
)
@property
def lower_optimized_joint_limits(self):
return cs.DM(
[
self.get_joint_lower_limit(jnt)
for jnt in self._urdf.joints
if jnt.name in self.optimized_joint_names
]
)
@property
def upper_optimized_joint_limits(self):
return cs.DM(
[
self.get_joint_upper_limit(jnt)
for jnt in self._urdf.joints
if jnt.name in self.optimized_joint_names
]
)
@property
def velocity_optimized_joint_limits(self):
return cs.DM(
[
self.get_velocity_joint_limit(jnt)
for jnt in self._urdf.joints
if jnt.name in self.optimized_joint_names
]
)
def add_base_frame(self, base_link, xyz=None, rpy=None, joint_name=None):
"""Add new base frame, note this changes the root link."""
parent_link = base_link
child_link = self._urdf.get_root() # i.e. current root
if xyz is None:
xyz = [0.0] * 3
if rpy is None:
rpy = [0.0] * 3
if not isinstance(joint_name, str):
joint_name = parent_link + "_and_" + child_link + "_joint"
self._urdf.add_link(Link(name=parent_link))
joint = Joint(
name=joint_name,
parent=parent_link,
child=child_link,
joint_type="fixed",
origin=Pose(xyz=xyz, rpy=rpy),
)
self._urdf.add_joint(joint)
def add_fixed_link(self, link, parent_link, xyz=None, rpy=None, joint_name=None):
"""Add a fixed link"""
assert link not in self.link_names, f"'{link}' already exists"
assert (
parent_link in self.link_names
), f"{parent_link=}, does not appear in link names"
child_link = link
if xyz is None:
xyz = [0.0] * 3
if rpy is None:
rpy = [0.0] * 3
if not isinstance(joint_name, str):
joint_name = parent_link + "_and_" + child_link + "_joint"
self._urdf.add_link(Link(name=child_link))
origin = Pose(xyz=xyz, rpy=rpy)
self._urdf.add_joint(
Joint(
name=joint_name,
parent=parent_link,
child=child_link,
joint_type="fixed",
origin=origin,
)
)
def get_root_link(self):
"""Return the root link"""
return self._urdf.get_root()
@staticmethod
def get_link_visual_origin(link):
xyz, rpy = cs.DM.zeros(3), cs.DM.zeros(3)
if link.visual is not None:
if link.visual.origin is not None:
origin = link.visual.origin
xyz, rpy = cs.DM(origin.xyz), cs.DM(origin.rpy)
return xyz, rpy
@staticmethod
def get_joint_origin(joint):
"""Get the origin for the joint"""
xyz, rpy = cs.DM.zeros(3), cs.DM.zeros(3)
if joint.origin is not None:
xyz, rpy = cs.DM(joint.origin.xyz), cs.DM(joint.origin.rpy)
return xyz, rpy
@staticmethod
def get_joint_axis(joint):
"""Get the axis of joint, the axis is normalized for revolute/continuous joints"""
axis = cs.DM(joint.axis) if joint.axis is not None else cs.DM([1.0, 0.0, 0.0])
return unit(axis)
def _get_actuated_joint_index(self, joint_name):
return self.actuated_joint_names.index(joint_name)
def get_random_joint_positions(
self, n=1, xlim=None, ylim=None, zlim=None, base_link=None
):
"""Return a random array with joint positions within the actuator limits."""
lo = self.lower_actuated_joint_limits.toarray()
hi = self.upper_actuated_joint_limits.toarray()
pos = None
if isinstance(base_link, str):
pos = {
self.get_link_position_function(link, base_link)
for link in self.link_names
}
def _in_limit(q):
if pos is not None:
for p in pos.values():
pp = p(q)
if xlim is not None:
if not (xlim[0] <= pp[0] <= xlim[1]):
return False
if ylim is not None:
if not (ylim[0] <= pp[1] <= ylim[1]):
return False
if zlim is not None:
if not (zlim[0] <= pp[2] <= zlim[1]):
return False
return True
def randq():
qr = cs.vec(cs.np.random.uniform(lo, hi))
while not _in_limit(qr):
qr = cs.vec(cs.np.random.uniform(lo, hi))
return qr
return cs.horzcat(*[randq() for _ in range(n)])
def get_random_pose_in_global_link(self, link):
"""Returns a random end-effector pose within the robot limits defined in the global link frame."""
q = self.get_random_joint_positions()
return self.get_global_link_transform(link, q)
def _make_function(self, label, link, method, n=1, base_link=None):
q = cs.SX.sym("q", self.ndof)
args = (link, q)
kwargs = {}
if base_link is not None:
kwargs["base_link"] = base_link
out = method(*args, **kwargs)
F = cs.Function(label, [q], [out])
if n > 1 and out.shape[1] == 1:
F = F.map(n)
elif n > 1 and out.shape[1] > 1:
class ListFunction:
def __init__(self, F, n):
self.F = F
self.n = n
@arrayify_args
def __call__(self, Q):
assert (
Q.shape[1] == self.n
), f"expected input to have shape {self.ndof}-by-{n}, got {Q.shape[0]}-by-{Q.shape[1]}"
return [self.F(q) for q in cs.horzsplit(Q)]
def size_in(self, i):
return self.F.size_in(i)
def size_out(self, i):
return self.F.size_out(i)
def size1_in(self, i):
return self.F.size1_in(i)
def size1_out(self, i):
return self.F.size1_out(i)
def size2_in(self, i):
return self.F.size2_in(i)
def size2_out(self, i):
return self.F.size2_out(i)
def numel_in(self):
return self.F.numel_in()
def numel_out(self):
return self.F.numel_out()
F = ListFunction(F, n)
return F
@arrayify_args
@listify_output
def get_global_link_transform(self, link, q):
"""Get the link transform in the global frame for a given joint state q"""
# Setup
assert (
link in self._urdf.link_map.keys()
), f"given link '{link}' does not appear in URDF"
root = self._urdf.get_root()
T = I4()
if link == root:
return T
# Iterate over joints in chain
for joint_name in self._urdf.get_chain(root, link, links=False):
joint = self._urdf.joint_map[joint_name]
xyz, rpy = self.get_joint_origin(joint)
if joint.type == "fixed":
T = T @ rt2tr(rpy2r(rpy), xyz)
continue
joint_index = self._get_actuated_joint_index(joint.name)
qi = q[joint_index]
T = T @ rt2tr(rpy2r(rpy), xyz)
if joint.type in {"revolute", "continuous"}:
T = T @ r2t(angvec2r(qi, self.get_joint_axis(joint)))
elif joint.type == "prismatic":
T = T @ rt2tr(I3(), qi * self.get_joint_axis(joint))
else:
raise JointTypeNotSupported(joint.type)
return T
def get_global_link_transform_function(self, link, n=1):
"""Get the function which computes the link transform in the global frame"""
return self._make_function("T", link, self.get_global_link_transform, n=n)
@arrayify_args
@listify_output
def get_link_transform(self, link, q, base_link):
"""Get the link transform in a given base frame."""
T_L_W = self.get_global_link_transform(link, q)
T_B_W = self.get_global_link_transform(base_link, q)
return T_L_W @ invt(T_B_W)
def get_link_transform_function(self, link, base_link, n=1):
"""Get the function that computes the transform in a given base frame"""
return self._make_function(
"T", link, self.get_link_transform, base_link=base_link, n=n
)
@arrayify_args
@listify_output
def get_global_link_position(self, link, q):
"""Get the link position in the global frame for a given joint state q"""
return transl(self.get_global_link_transform(link, q))
def get_global_link_position_function(self, link, n=1):
"""Get the function that computes the global position of a given link"""
return self._make_function("p", link, self.get_global_link_position, n=n)
@arrayify_args
@listify_output
def get_link_position(self, link, q, base_link):
"""Get the link position in a given base frame"""
return transl(self.get_link_transform(link, q, base_link))
def get_link_position_function(self, link, base_link, n=1):
"""Get the function that computes the position of a link in a given base frame."""
return self._make_function(
"p", link, self.get_link_position, n=n, base_link=base_link
)
@arrayify_args
@listify_output
def get_global_link_rotation(self, link, q):
"""Get the link rotation in the global frame for a given joint state q"""
return t2r(self.get_global_link_transform(link, q))
def get_global_link_rotation_function(self, link, n=1):
"""Get the function that computes a rotation matrix in the global link"""
return self._make_function("R", link, self.get_global_link_rotation, n=n)
@arrayify_args
@listify_output
def get_link_rotation(self, link, q, base_link):
"""Get the rotation matrix for a link in a given base frame"""
return t2r(self.get_link_transform(link, q, base_link))
def get_link_rotation_function(self, link, base_link, n=1):
"""Get the function that computes the rotation matrix for a link in a given base frame."""
return self._make_function(
"R", link, self.get_link_rotation, base_link=base_link, n=n
)
@arrayify_args
@listify_output
def get_global_link_quaternion(self, link, q):
"""Get a quaternion in the global frame."""
# Setup
assert link in self._urdf.link_map.keys(), "given link does not appear in URDF"
root = self._urdf.get_root()
quat = Quaternion(0.0, 0.0, 0.0, 1.0)
if link == root:
return quat.getquat()
# Iterate over joints in chain
for joint_name in self._urdf.get_chain(root, link, links=False):
joint = self._urdf.joint_map[joint_name]
xyz, rpy = self.get_joint_origin(joint)
if joint.type == "fixed":
quat = Quaternion.fromrpy(rpy) * quat
continue
joint_index = self._get_actuated_joint_index(joint.name)
qi = q[joint_index]
quat = Quaternion.fromrpy(rpy) * quat
if joint.type in {"revolute", "continuous"}:
quat = Quaternion.fromangvec(qi, self.get_joint_axis(joint)) * quat
elif joint.type == "prismatic":
pass
else:
raise JointTypeNotSupported(joint.type)
return quat.getquat()
def get_global_link_quaternion_function(self, link, n=1):
"""Get the function that computes a quaternion in the global frame."""
return self._make_function("quat", link, self.get_global_link_quaternion, n=n)
@arrayify_args
@listify_output
def get_link_quaternion(self, link, q, base_link):
"""Get the quaternion defined in a given base frame."""
quat_L_W = Quaternion(self.get_global_link_quaternion(link, q))
quat_B_W = Quaternion(self.get_global_link_quaternion(base_link, q))
return (quat_L_W * quat_B_W.inv()).getquat()
def get_link_quaternion_function(self, link, base_link, n=1):
"""Get the function that computes a quaternion defined in a given base frame."""
return self._make_function(
"quat", link, self.get_link_quaternion, n=n, base_link=base_link
)
@arrayify_args
@listify_output
def get_global_link_rpy(self, link, q):
"""Get the Roll-Pitch-Yaw angles in the global frame."""
return Quaternion(self.get_global_link_quaternion(link, q)).getrpy()
def get_global_link_rpy_function(self, link, n=1):
"""Get the function that computes the Roll-Pitch-Yaw angles in the global frame."""
return self._make_function("quat", link, self.get_global_link_rpy, n=n)
@arrayify_args
@listify_output
def get_link_rpy(self, link, q, base_link):
"""Get the the Roll-Pitch-Yaw angles defined in a given base frame."""
return Quaternion(self.get_link_quaternion(link, q, base_link)).getrpy()
def get_link_rpy_function(self, link, base_link, n=1):
"""Get the function that computes the Roll-Pitch-Yaw angles defined in a given base frame."""
return self._make_function(
"quat", link, self.get_link_rpy, n=n, base_link=base_link
)
@deprecation_warning("get_global_link_geometric_jacobian")
def get_global_geometric_jacobian(self, link, q):
pass
@arrayify_args
@listify_output
def get_global_link_geometric_jacobian(self, link, q):
"""Compute the geometric Jacobian matrix in the global frame."""
e = self.get_global_link_position(link, q)
w = cs.DM.zeros(3)
pdot = cs.DM.zeros(3)
joint_index_order = []
jacobian_columns = []
past_in_chain = False
for joint in self._urdf.joints:
if joint.type == "fixed":
continue
if joint.child == link:
past_in_chain = True
joint_index = self._get_actuated_joint_index(joint.name)
joint_index_order.append(joint_index)
qi = q[joint_index]
if past_in_chain:
jcol = cs.DM.zeros(6)
jacobian_columns.append(jcol)
elif joint.type in {"revolute", "continuous"}:
axis = self.get_joint_axis(joint)
R = self.get_global_link_rotation(joint.child, q)
R = R @ angvec2r(qi, axis)
p = self.get_global_link_position(joint.child, q)
z = R @ axis
pdot = cs.cross(z, e - p)
jcol = cs.vertcat(pdot, z)
jacobian_columns.append(jcol)
elif joint.type == "prismatic":
axis = self.get_joint_axis(joint)
R = self.get_global_link_rotation(joint.child, q)
z = R @ axis
jcol = cs.vertcat(z, cs.DM.zeros(3))
jacobian_columns.append(jcol)
else:
raise JointTypeNotSupported(joint.type)
# Sort columns of jacobian
jacobian_columns_ordered = [jacobian_columns[idx] for idx in joint_index_order]
# Build jacoian array
J = jacobian_columns_ordered.pop(0)
while jacobian_columns_ordered:
J = cs.horzcat(J, jacobian_columns_ordered.pop(0))
return J
@deprecation_warning("get_global_link_geometric_jacobian_function")
def get_global_geometric_jacobian_function(self, link, n=1):
pass
def get_global_link_geometric_jacobian_function(self, link, n=1):
"""Get the function that computes the geometric jacobian in the global frame."""
return self._make_function(
"J", link, self.get_global_link_geometric_jacobian, n=n
)
@deprecation_warning("get_global_link_analytical_jacobian")
def get_global_analytical_jacobian(self, link, q):
pass
@arrayify_args
@listify_output
def get_global_link_analytical_jacobian(self, link, q):
"""Compute the analytical Jacobian matrix in the global frame."""
return cs.vertcat(
self.get_global_link_linear_jacobian(link, q),
self.get_global_link_angular_analytical_jacobian(link, q),
)
@deprecation_warning("get_global_link_analytical_jacobian_function")
def get_global_analytical_jacobian_function(self, link):
pass
def get_global_link_analytical_jacobian_function(self, link):
"""Get the function that computes the analytical jacobian in the global frame."""
return self._make_function(
"J_a", link, self.get_global_link_analytical_jacobian
)
@deprecation_warning("get_link_geometric_jacobian")
def get_geometric_jacobian(self):
pass
@arrayify_args
@listify_output
def get_link_geometric_jacobian(self, link, q, base_link):
"""Get the geometric jacobian in a given base link."""
J = self.get_global_link_geometric_jacobian(link, q)
# Transform jacobian to given base link
R = self.get_global_link_rotation(base_link, q).T
O = cs.DM.zeros(3, 3)
K = cs.vertcat(
cs.horzcat(R, O),
cs.horzcat(O, R),
)
J = K @ J
return J
@deprecation_warning("get_link_geometric_jacobian_function")
def get_geometric_jacobian_function(self, link, base_link, n=1):
pass
def get_link_geometric_jacobian_function(self, link, base_link, n=1):
"""Get the function that computes the geometric jacobian in a given base frame"""
return self._make_function(
"J", link, self.get_link_geometric_jacobian, base_link=base_link, n=n
)