-
Notifications
You must be signed in to change notification settings - Fork 499
/
Copy pathERobot.py
2260 lines (1874 loc) · 75.5 KB
/
ERobot.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
#!/usr/bin/env python3
"""
Created on Tue Apr 24 15:48:52 2020
@author: Jesse Haviland
"""
from os.path import splitext
import tempfile
import subprocess
import webbrowser
import numpy as np
from spatialmath import SE3, SE2
from spatialmath.base.argcheck import getvector, verifymatrix, getmatrix, \
islistof
from roboticstoolbox.robot.ELink import ELink, ELink2, BaseELink
from roboticstoolbox.robot.ETS import ETS, ETS2
from roboticstoolbox.robot.DHRobot import DHRobot
from roboticstoolbox.tools import xacro
from roboticstoolbox.tools import URDF
from roboticstoolbox.robot.Robot import Robot
from roboticstoolbox.robot.Gripper import Gripper
from roboticstoolbox.tools.data import path_to_datafile
from pathlib import PurePosixPath
from ansitable import ANSITable, Column
from spatialmath import SpatialAcceleration, SpatialVelocity, \
SpatialInertia, SpatialForce
import fknm
class BaseERobot(Robot):
"""
Construct an ERobot object
:param et_list: List of elementary transforms which represent the robot
kinematics
:type et_list: ET list
:param name: Name of the robot
:type name: str, optional
:param manufacturer: Manufacturer of the robot
:type manufacturer: str, optional
:param base: Location of the base is the world frame
:type base: SE3, optional
:param tool: Offset of the flange of the robot to the end-effector
:type tool: SE3, optional
:param gravity: The gravity vector
:type n: ndarray(3)
An ERobot represents the kinematics of a serial-link manipulator with
one or more branches.
From ETS
--------
Example:
.. runblock:: pycon
>>> from roboticstoolbox import ETS, ERobot
>>> ets = ETS.rz() * ETS.ry() * ETS.tz(1) * ETS.ry() * ETS.tz(1)
>>> robot = ERobot(ets)
>>> print(robot)
The ETS is partitioned such that a new link frame is created **after** every
joint variable.
From list of ELinks
-------------------
Example:
.. runblock:: pycon
>>> from roboticstoolbox import ETS, ERobot
>>> link1 = ELink(ETS.rz(), name='link1')
>>> link2 = ELink(ETS.ry(), name='link2', parent=link1)
>>> link3 = ELink(ETS.tz(1) * ETS.ry(), name='link3', parent=link2)
>>> link4 = ELink(ETS.tz(1), name='ee', parent=link3)
>>> robot = ERobot([link1, link2, link3, link4])
>>> print(robot)
A number of ``ELink`` objects are created, each has a transform with
respect to the previous frame, and all except the first link have a parent.
The implicit parent of the first link is the base.
The parent also can be specified as a string, and its name is mapped to the
parent link by name in ``ERobot``.
If no ``parent`` arguments are given it is assumed the links are in
sequential order, and the parent hierarchy will be automatically
established.
.. runblock:: pycon
>>> from roboticstoolbox import ETS, ERobot
>>> robot = ERobot([
>>> ELink(ETS.rz(), name='link1'),
>>> ELink(ETS.ry(), name='link2'),
>>> ELink(ETS.tz(1) * ETS.ry(), name='link3'),
>>> ELink(ETS.tz(1), name='ee')
>>> ])
>>> print(robot)
Branched robots
---------------
Example:
.. runblock:: pycon
>>> robot = ERobot([
>>> ELink(ETS.rz(), name='link1'),
>>> ELink(ETS.tx(1) * ETS.ty(-0.5) * ETS.rz(), name='link2', parent='link1'),
>>> ELink(ETS.tx(1), name='ee_1', parent='link2'),
>>> ELink(ETS.tx(1) * ETS.ty(0.5) * ETS.rz(), name='link3', parent='link1'),
>>> ELink(ETS.tx(1), name='ee_2', parent='link3')
>>> ])
>>> print(robot)
:references:
- Kinematic Derivatives using the Elementary Transform Sequence,
J. Haviland and P. Corke
""" # noqa E501
def __init__(
self,
links,
base_link=None,
gripper_links=None,
checkjindex=True,
**kwargs
):
self._ets = []
self._linkdict = {}
self._n = 0
self._ee_links = []
self._base_link = None
# Ordered links, we reorder the input elinks to be in depth first
# search order
orlinks = []
# check all the incoming ELink objects
n = 0
for k, link in enumerate(links):
# if link has no name, give it one
if link.name is None:
link.name = f"link-{k}"
link.number = k
# put it in the link dictionary, check for duplicates
if link.name in self._linkdict:
raise ValueError(
f'link name {link.name} is not unique')
self._linkdict[link.name] = link
if link.isjoint:
n += 1
# resolve parents given by name, within the context of
# this set of links
for link in links:
if isinstance(link.parent, str):
link._parent = self._linkdict[link.parent]
if all([link.parent is None for link in links]):
# no parent links were given, assume they are sequential
for i in range(len(links) - 1):
links[i + 1]._parent = links[i]
self._n = n
# scan for base
for link in links:
# is this a base link?
if link._parent is None:
if self._base_link is not None:
raise ValueError('Multiple base links')
self._base_link = link
else:
# no, update children of this link's parent
link._parent._children.append(link)
# Set up the gripper, make a list containing the root of all
# grippers
if gripper_links is not None:
if isinstance(gripper_links, ELink):
gripper_links = [gripper_links]
else:
gripper_links = []
# An empty list to hold all grippers
self.grippers = []
# Make a gripper object for each gripper
for link in gripper_links:
g_links = self.dfs_links(link)
# Remove gripper links from the robot
for g_link in g_links:
links.remove(g_link)
# Save the gripper object
self.grippers.append(Gripper(g_links))
# Subtract the n of the grippers from the n of the robot
for gripper in self.grippers:
self._n -= gripper.n
# Set the ee links
self.ee_links = []
if len(gripper_links) == 0:
for link in links:
# is this a leaf node? and do we not have any grippers
if len(link.children) == 0:
# no children, must be an end-effector
self.ee_links.append(link)
else:
for link in gripper_links:
# use the passed in value
self.ee_links.append(link.parent)
# assign the joint indices
if all([link.jindex is None for link in links]):
# no joints have an index
jindex = [0] # "mutable integer" hack
def visit_link(link, jindex):
# if it's a joint, assign it a jindex and increment it
if link.isjoint and link in links:
link.jindex = jindex[0]
jindex[0] += 1
if link in links:
orlinks.append(link)
# visit all links in DFS order
self.dfs_links(
self.base_link, lambda link: visit_link(link, jindex))
elif all([link.jindex is not None for link in links if link.isjoint]):
# jindex set on all, check they are unique and contiguous
if checkjindex:
jset = set(range(self._n))
for link in links:
if link.isjoint and link.jindex not in jset:
raise ValueError(
f'joint index {link.jindex} was '
'repeated or out of range')
jset -= set([link.jindex])
if len(jset) > 0: # pragma nocover # is impossible
raise ValueError(f'joints {jset} were not assigned')
orlinks = links
else:
# must be a mixture of ELinks with/without jindex
raise ValueError(
'all links must have a jindex, or none have a jindex')
self._nbranches = sum([link.nchildren == 0 for link in links])
# Current joint angles of the robot
# TODO should go to Robot class?
self.q = np.zeros(self.n)
self.qd = np.zeros(self.n)
self.qdd = np.zeros(self.n)
self.control_type = 'v'
# Set up qlim
qlim = np.zeros((2, self.n))
j = 0
for i in range(len(orlinks)):
if orlinks[i].isjoint:
qlim[:, j] = orlinks[i].qlim
j += 1
self._qlim = qlim
for i in range(self.n):
if np.any(qlim[:, i] != 0) and \
not np.any(np.isnan(qlim[:, i])):
self._valid_qlim = True
super().__init__(orlinks, **kwargs)
def __str__(self):
"""
Pretty prints the ETS Model of the robot.
:return: Pretty print of the robot model
:rtype: str
.. note::
- Constant links are shown in blue.
- End-effector links are prefixed with an @
- Angles in degrees
- The robot base frame is denoted as ``BASE`` and is equal to the
robot's ``base`` attribute.
"""
table = ANSITable(
Column("id", headalign="^", colalign=">"),
Column("link", headalign="^", colalign="<"),
Column("joint", headalign="^", colalign=">"),
Column("parent", headalign="^", colalign="<"),
Column("ETS", headalign="^", colalign="<"),
border="thin")
for link in self:
color = "" if link.isjoint else "<<blue>>"
ee = "@" if link in self.ee_links else ""
ets = link.ets()
if link.parent is None:
parent_name = "BASE"
else:
parent_name = link.parent.name
s = ets.__str__(f"q{link._jindex}")
if len(s) > 0:
s = " \u2295 " + s
if link.isjoint:
if link._joint_name is not None:
jname = link._joint_name
else:
jname = link.jindex
else:
jname = ''
table.row(
link.number,
color + ee + link.name,
jname,
parent_name,
f"{{{link.name}}} = {{{parent_name}}}{s}"
)
if isinstance(self, ERobot):
classname = 'ERobot'
elif isinstance(self, ERobot2):
classname = 'ERobot2'
s = f"{classname}: {self.name}"
if self.manufacturer is not None and len(self.manufacturer) > 0:
s += f" (by {self.manufacturer})"
s += f", {self.n} joints ({self.structure})"
if self.nbranches > 1:
s += f", {self.nbranches} branches"
if self._hasdynamics:
s += ", dynamics"
if any([len(link.geometry) > 0 for link in self.links]):
s += ", geometry"
if any([len(link.collision) > 0 for link in self.links]):
s += ", collision"
s += "\n"
s += str(table)
s += self.configurations_str()
return s
def hierarchy(self):
"""
Pretty print the robot link hierachy
:return: Pretty print of the robot model
:rtype: str
Example:
.. runblock:: pycon
>>> import roboticstoolbox as rtb
>>> robot = rtb.models.URDF.Panda()
>>> robot.hierarchy()
"""
# link = self.base_link
def recurse(link, indent=0):
print(' ' * indent * 2, link.name)
for child in link.child:
recurse(child, indent + 1)
recurse(self.base_link)
# @property
# def qlim(self):
# return self._qlim
# @property
# def valid_qlim(self):
# return self._valid_qlim
# --------------------------------------------------------------------- #
@property
def n(self):
"""
Number of joints
:return: number of variable joint in the robot's kinematic tree
:rtype: int
The sum of the number of revolute and prismatic joints.
"""
return self._n
# --------------------------------------------------------------------- #
@property
def nbranches(self):
"""
Number of branches
:return: number of branches in the robot's kinematic tree
:rtype: int
Number of branches in this robot. Computed as the number of links with
zero children
Example:
.. runblock:: pycon
>>> import roboticstoolbox as rtb
>>> robot = rtb.models.ETS.Panda()
>>> robot.nbranches
:seealso: :func:`n`, :func:`nlinks`
"""
return self._nbranches
# --------------------------------------------------------------------- #
@property
def elinks(self):
# return self._linkdict
return self._links
# --------------------------------------------------------------------- #
@property
def link_dict(self):
return self._linkdict
# --------------------------------------------------------------------- #
@property
def base_link(self):
return self._base_link
@base_link.setter
def base_link(self, link):
if isinstance(link, ELink):
self._base_link = link
else:
# self._base_link = self.links[link]
raise TypeError('Must be an ELink')
# self._reset_fk_path()
# --------------------------------------------------------------------- #
# TODO get configuration string
@property
def ee_links(self):
return self._ee_links
# def add_ee(self, link):
# if isinstance(link, ELink):
# self._ee_link.append(link)
# else:
# raise ValueError('must be an ELink')
# self._reset_fk_path()
@ee_links.setter
def ee_links(self, link):
if isinstance(link, ELink):
self._ee_links = [link]
elif isinstance(link, list) and \
all([isinstance(x, ELink) for x in link]):
self._ee_links = link
else:
raise TypeError('expecting an ELink or list of ELinks')
# self._reset_fk_path()
@property
def reach(self):
r"""
Reach of the robot
:return: Maximum reach of the robot
:rtype: float
A conservative estimate of the reach of the robot. It is computed as
the sum of the translational ETs that define the link transform.
.. note::
- Probably an overestimate of reach
- Used by numerical inverse kinematics to scale translational
error.
- For a prismatic joint, uses ``qlim`` if it is set
.. warning:: Computed on the first access. If kinematic parameters
subsequently change this will not be reflected.
"""
if self._reach is None:
d_all = []
for link in self.ee_links:
d = 0
while True:
for et in link.ets():
if et.istranslation:
if et.isjoint:
# the length of a prismatic joint depends on the
# joint limits. They might be set in the ET
# or in the Link depending on how the robot
# was constructed
if link.qlim is not None:
d += max(link.qlim)
elif et.qlim is not None:
d += max(et.qlim)
else:
d += abs(et.eta)
link = link.parent
if link is None:
d_all.append(d)
break
self._reach = max(d_all)
return self._reach
# --------------------------------------------------------------------- #
# @property
# def ets(self):
# return self._ets
# --------------------------------------------------------------------- #
# @property
# def M(self):
# return self._M
# --------------------------------------------------------------------- #
# @property
# def q_idx(self):
# return self._q_idx
# --------------------------------------------------------------------- #
def ets(self, start=None, end=None, explored=None, path=None):
"""
ERobot to ETS
:param start: start of path, defaults to ``base_link``
:type start: ELink or str, optional
:param end: end of path, defaults to end-effector
:type end: ELink or str, optional
:raises ValueError: a link does not belong to this ERobot
:raises TypeError: a bad link argument
:return: elementary transform sequence
:rtype: ETS instance
- ``robot.ets()`` is an ETS representing the kinematics from base to
end-effector.
- ``robot.ets(end=link)`` is an ETS representing the kinematics from
base to the link ``link`` specified as an ELink reference or a name.
- ``robot.ets(start=l1, end=l2)`` is an ETS representing the kinematics
from link ``l1`` to link ``l2``.
.. runblock:: pycon
>>> import roboticstoolbox as rtb
>>> panda = rtb.models.ETS.Panda()
>>> panda.ets()
"""
link = self._getlink(start, self.base_link)
if end is None and len(self.ee_links) > 1:
raise ValueError(
'ambiguous, specify which end-effector is required')
end = self._getlink(end, self.ee_links[0])
if explored is None:
explored = set()
toplevel = path is None
explored.add(link)
if link == end:
return path
# unlike regular DFS, the neighbours of the node are its children
# and its parent.
# visit child nodes below start
if toplevel:
path = link.ets()
for child in link.children:
if child not in explored:
p = self.ets(child, end, explored, path * child.ets())
if p is not None:
return p
# we didn't find the node below, keep going up a level, and recursing
# down again
if toplevel:
path = None
if link.parent is not None:
parent = link.parent # go up one level toward the root
if parent not in explored:
if path is None:
p = self.ets(parent, end, explored, link.ets().inv())
else:
p = self.ets(parent, end, explored, path * link.ets().inv())
if p is not None:
return p
return None
# --------------------------------------------------------------------- #
def segments(self):
"""
Segments of branched robot
:return: Segment list
:rtype: list of lists of Link
For a single-chain robot with structure::
L1 - L2 - L3
the return is ``[[None, L1, L2, L3]]``
For a robot with structure::
L1 - L2 +- L3 - L4
+- L5 - L6
the return is ``[[None, L1, L2], [L2, L3, L4], [L2, L5, L6]]``
.. note::
- the length of the list is the number of segments in the robot
- the first segment always starts with ``None`` which represents
the base transform (since there is no base link)
- the last link of one segment is also the first link of subsequent
segments
"""
def recurse(link):
segs = [link.parent]
while True:
segs.append(link)
if link.nchildren == 0:
return segs
elif link.nchildren == 1:
link = link.children[0]
continue
elif link.nchildren > 1:
segs = [segs]
for child in link.children:
segs.append(recurse(child))
return segs
return recurse(self.links[0])
# --------------------------------------------------------------------- #
def fkine_path(self, q, old=None):
'''
Compute the pose of every link frame
:param q: The joint configuration
:type q: darray(n)
:return: Pose of all links
:rtype: SE3 instance
``T = robot.fkine_path(q)`` is an SE3 instance with ``robot.nlinks +
1`` values:
- ``T[0]`` is the base transform
- ``T[i+1]`` is the pose of link whose ``number`` is ``i``
:references:
- Kinematic Derivatives using the Elementary Transform
Sequence, J. Haviland and P. Corke
'''
q = getvector(q)
Tbase = self.base # add base, also sets the type
linkframes = Tbase.__class__.Alloc(self.nlinks + 1)
linkframes[0] = Tbase
def recurse(Tall, Tparent, q, link):
# if joint??
T = Tparent
while True:
T *= link.A(q[link.jindex])
Tall[link.number + 1] = T
if link.nchildren == 1:
link = link.children[0]
continue
elif link.nchildren == 0:
return
else:
# multiple children
for child in link.children:
recurse(Tall, T, q, child)
return
recurse(linkframes, Tbase, q, self.links[0])
return linkframes
# --------------------------------------------------------------------- #
def showgraph(self, **kwargs):
"""
Display a link transform graph in browser
:param etsbox: Put the link ETS in a box, otherwise an edge label
:type etsbox: bool
:param jtype: Arrowhead to node indicates revolute or prismatic type
:type jtype: bool
:param static: Show static joints in blue and bold
:type static: bool
``robot.showgraph()`` displays a graph of the robot's link frames
and the ETS between them. It uses GraphViz dot.
The nodes are:
- Base is shown as a grey square. This is the world frame origin,
but can be changed using the ``base`` attribute of the robot.
- Link frames are indicated by circles
- ETS transforms are indicated by rounded boxes
The edges are:
- an arrow if `jtype` is False or the joint is fixed
- an arrow with a round head if `jtype` is True and the joint is
revolute
- an arrow with a box head if `jtype` is True and the joint is
prismatic
Edge labels or nodes in blue have a fixed transformation to the
preceding link.
Example::
>>> import roboticstoolbox as rtb
>>> panda = rtb.models.URDF.Panda()
>>> panda.showgraph()
.. image:: ../figs/panda-graph.svg
:width: 600
:seealso: :func:`dotfile`
"""
# create the temporary dotfile
dotfile = tempfile.TemporaryFile(mode="w")
self.dotfile(dotfile, **kwargs)
# rewind the dot file, create PDF file in the filesystem, run dot
dotfile.seek(0)
pdffile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
subprocess.run("dot -Tpdf", shell=True, stdin=dotfile, stdout=pdffile)
# open the PDF file in browser (hopefully portable), then cleanup
webbrowser.open(f"file://{pdffile.name}")
# time.sleep(1)
# os.remove(pdffile.name)
def dotfile(self, filename, etsbox=False, jtype=False, static=True):
"""
Write a link transform graph as a GraphViz dot file
:param file: Name of file to write to
:type file: str or file
:param etsbox: Put the link ETS in a box, otherwise an edge label
:type etsbox: bool
:param jtype: Arrowhead to node indicates revolute or prismatic type
:type jtype: bool
:param static: Show static joints in blue and bold
:type static: bool
The file can be processed using dot::
% dot -Tpng -o out.png dotfile.dot
The nodes are:
- Base is shown as a grey square. This is the world frame origin,
but can be changed using the ``base`` attribute of the robot.
- Link frames are indicated by circles
- ETS transforms are indicated by rounded boxes
The edges are:
- an arrow if `jtype` is False or the joint is fixed
- an arrow with a round head if `jtype` is True and the joint is
revolute
- an arrow with a box head if `jtype` is True and the joint is
prismatic
Edge labels or nodes in blue have a fixed transformation to the
preceding link.
.. note:: If ``filename`` is a file object then the file will *not*
be closed after the GraphViz model is written.
:seealso: :func:`showgraph`
"""
if isinstance(filename, str):
file = open(filename, 'w', encoding='utf-8')
else:
file = filename
header = r"""digraph G {
graph [rankdir=LR];
"""
def draw_edge(link, etsbox, jtype, static):
# draw the edge
if jtype:
if link.isprismatic:
edge_options = \
'arrowhead="box", arrowtail="inv", dir="both"'
elif link.isrevolute:
edge_options = \
'arrowhead="dot", arrowtail="inv", dir="both"'
else:
edge_options = 'arrowhead="normal"'
else:
edge_options = 'arrowhead="normal"'
if link.parent is None:
parent = 'BASE'
else:
parent = link.parent.name
if etsbox:
# put the ets fragment in a box
if not link.isjoint and static:
node_options = ', fontcolor="blue"'
else:
node_options = ''
file.write(
' {}_ets [shape=box, style=rounded, '
'label="{}"{}];\n'.format(
link.name, link.ets().__str__(
q=f"q{link.jindex}"), node_options))
file.write(' {} -> {}_ets;\n'.format(parent, link.name))
file.write(' {}_ets -> {} [{}];\n'.format(
link.name, link.name, edge_options))
else:
# put the ets fragment as an edge label
if not link.isjoint and static:
edge_options += 'fontcolor="blue"'
file.write(' {} -> {} [label="{}", {}];\n'.format(
parent, link.name, link.ets().__str__(
q=f"q{link.jindex}"), edge_options))
file.write(header)
# add the base link
file.write(' BASE [shape=square, style=filled, fillcolor=gray]\n')
# add the links
for link in self:
# draw the link frame node (circle) or ee node (doublecircle)
if link in self.ee_links:
# end-effector
node_options = \
'shape="doublecircle", color="blue", fontcolor="blue"'
else:
node_options = 'shape="circle"'
file.write(' {} [{}];\n'.format(link.name, node_options))
draw_edge(link, etsbox, jtype, static)
for gripper in self.grippers:
for link in gripper.links:
file.write(' {} [shape=cds];\n'.format(link.name))
draw_edge(link, etsbox, jtype, static)
file.write('}\n')
if isinstance(filename, str):
file.close() # noqa
def dfs_links(self, start, func=None):
"""
Visit all links from start in depth-first order and will apply
func to each visited link
:param start: the link to start at
:type start: ELink
:param func: An optional function to apply to each link as it is found
:type func: function
:returns: A list of links
:rtype: list of ELink
"""
visited = []
def vis_children(link):
visited.append(link)
if func is not None:
func(link)
for li in link.children:
if li not in visited:
vis_children(li)
vis_children(start)
return visited
def _get_limit_links(self, end=None, start=None):
"""
Get and validate an end-effector, and a base link
:param end: end-effector or gripper to compute forward kinematics to
:type end: str or ELink or Gripper, optional
:param start: name or reference to a base link, defaults to None
:type start: str or ELink, optional
:raises ValueError: link not known or ambiguous
:raises ValueError: [description]
:raises TypeError: unknown type provided
:return: end-effector link, base link, and tool transform of gripper
if applicable
:rtype: ELink, Elink, SE3 or None
Helper method to find or validate an end-effector and base link.
"""
# Try cache
# if self._cache_end is not None:
# return self._cache_end, self._cache_start, self._cache_end_tool
tool = None
if end is None:
# if we have a gripper, use it
if len(self.grippers) == 1:
end = self.grippers[0].links[0]
tool = self.grippers[0].tool
elif len(self.grippers) > 1:
# if more than one gripper, user must choose
raise ValueError('Must specify which gripper')
# no grippers, use ee link if just one
elif len(self.ee_links) == 1:
end = self.ee_links[0]
else:
# if more than one EE, user must choose
raise ValueError('Must specify which end-effector')
# Cache result
self._cache_end = end
self._cache_end_tool = tool
else:
# Check if end corresponds to gripper
for gripper in self.grippers:
if end == gripper or end == gripper.name:
tool = gripper.tool
end = gripper.links[0]
# otherwise check for end in the links
end = self._getlink(end)
if start is None:
start = self.base_link
# Cache result
self._cache_start = start
else:
# start effector is specified
start = self._getlink(start)
return end, start, tool
def _getlink(self, link, default=None):
"""
Validate reference to ELink
:param link: link
:type link: ELink or str
:raises ValueError: link does not belong to this ERobot
:raises TypeError: bad argument
:return: link reference
:rtype: ELink
``robot._getlink(link)`` is a validated reference to an ELink within
the ERobot ``robot``. If ``link`` is:
- an ``ELink`` reference it is validated as belonging to
``robot``.
- a string, then it looked up in the robot's link name dictionary, and
an ELink reference returned.
"""
if link is None:
link = default
if isinstance(link, str):
if link in self.link_dict:
return self.link_dict[link]
raise ValueError(f'no link named {link}')
elif isinstance(link, BaseELink):
if link in self.links:
return link
else:
for gripper in self.grippers:
if link in gripper.links:
return link
raise ValueError('link not in robot links')
else:
raise TypeError('unknown argument')
# =========================================================================== #
class ERobot(BaseERobot):
def __init__(self, arg, **kwargs):
if isinstance(arg, DHRobot):
# we're passed a DHRobot object
# TODO handle dynamic parameters if given
arg = arg.ets()
if isinstance(arg, ETS):
# we're passed an ETS string
ets = arg
links = []
# chop it up into segments, a link frame after every joint
parent = None
for j, ets_j in enumerate(arg.split()):
elink = ELink(ets_j, parent=parent, name=f"link{j:d}")
if elink.qlim is none and elink.v.qlim is not None:
elink.qlim = elink.v.qlim
parent = elink
links.append(elink)
elif islistof(arg, ELink):
links = arg
else:
raise TypeError(
'constructor argument must be ETS or list of ELink')
super().__init__(links, **kwargs)
# Cached paths through links