kinpy 0.4.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kinpy/__init__.py +20 -0
- kinpy/chain.py +238 -0
- kinpy/frame.py +120 -0
- kinpy/ik.py +24 -0
- kinpy/jacobian.py +77 -0
- kinpy/mjcf.py +116 -0
- kinpy/mjcf_parser/schema.xml +1926 -0
- kinpy/sdf.py +99 -0
- kinpy/transform.py +62 -0
- kinpy/urdf.py +139 -0
- kinpy/visualizer.py +262 -0
- kinpy-0.4.3.dist-info/METADATA +14 -0
- kinpy-0.4.3.dist-info/RECORD +15 -0
- kinpy-0.4.3.dist-info/WHEEL +4 -0
- kinpy-0.4.3.dist-info/licenses/LICENSE +21 -0
kinpy/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from .chain import Chain
|
|
4
|
+
from .mjcf import *
|
|
5
|
+
from .sdf import *
|
|
6
|
+
from .transform import *
|
|
7
|
+
from .urdf import *
|
|
8
|
+
from .visualizer import *
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def build_chain_from_file(filename: str) -> Chain:
|
|
12
|
+
ext = os.path.splitext(filename)[-1]
|
|
13
|
+
if ext == ".urdf":
|
|
14
|
+
return build_chain_from_urdf(open(filename).read())
|
|
15
|
+
elif ext == ".sdf":
|
|
16
|
+
return build_chain_from_sdf(open(filename).read())
|
|
17
|
+
elif ext == ".mjcf":
|
|
18
|
+
return build_chain_from_mjcf(open(filename).read())
|
|
19
|
+
else:
|
|
20
|
+
raise ValueError(f"Invalid file type: '{ext}' file.")
|
kinpy/chain.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
from functools import cached_property
|
|
2
|
+
from typing import Dict, Iterator, List, Optional, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from . import frame, ik, jacobian, transform
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Chain:
|
|
10
|
+
"""Chain is a class that represents a kinematic chain."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, root_frame: frame.Frame) -> None:
|
|
13
|
+
self._root: Optional[frame.Frame] = root_frame
|
|
14
|
+
|
|
15
|
+
def __str__(self) -> str:
|
|
16
|
+
return str(self._root)
|
|
17
|
+
|
|
18
|
+
def __iter__(self) -> Iterator[frame.Frame]:
|
|
19
|
+
assert self._root is not None, "Root frame is None"
|
|
20
|
+
yield from self._root.walk()
|
|
21
|
+
|
|
22
|
+
@cached_property
|
|
23
|
+
def dof(self):
|
|
24
|
+
return len(self.get_joint_parameter_names())
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def _find_frame_recursive(name: str, frame: frame.Frame) -> Optional[frame.Frame]:
|
|
28
|
+
for child in frame.children:
|
|
29
|
+
if child.name == name:
|
|
30
|
+
return child
|
|
31
|
+
ret = Chain._find_frame_recursive(name, child)
|
|
32
|
+
if ret is not None:
|
|
33
|
+
return ret
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
def find_frame(self, name: str) -> Optional[frame.Frame]:
|
|
37
|
+
"""Find a frame by name.
|
|
38
|
+
|
|
39
|
+
Parameters
|
|
40
|
+
----------
|
|
41
|
+
name : str
|
|
42
|
+
Frame name.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
Optional[frame.Frame]
|
|
47
|
+
Frame if found, None otherwise.
|
|
48
|
+
"""
|
|
49
|
+
assert self._root is not None, "Root frame is None"
|
|
50
|
+
if self._root.name == name:
|
|
51
|
+
return self._root
|
|
52
|
+
return self._find_frame_recursive(name, self._root)
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def _find_link_recursive(name: str, frame: frame.Frame) -> Optional[frame.Link]:
|
|
56
|
+
for child in frame.children:
|
|
57
|
+
if child.link.name == name:
|
|
58
|
+
return child.link
|
|
59
|
+
ret = Chain._find_link_recursive(name, child)
|
|
60
|
+
if ret is not None:
|
|
61
|
+
return ret
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
def find_link(self, name: str) -> Optional[frame.Link]:
|
|
65
|
+
"""Find a link by name.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
name : str
|
|
70
|
+
Link name.
|
|
71
|
+
|
|
72
|
+
Returns
|
|
73
|
+
-------
|
|
74
|
+
Optional[frame.Link]
|
|
75
|
+
Link if found, None otherwise.
|
|
76
|
+
"""
|
|
77
|
+
assert self._root is not None, "Root frame is None"
|
|
78
|
+
if self._root.link.name == name:
|
|
79
|
+
return self._root.link
|
|
80
|
+
return self._find_link_recursive(name, self._root)
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _get_joint_parameter_names(frame: frame.Frame, exclude_fixed: bool = True) -> List[str]:
|
|
84
|
+
joint_names = []
|
|
85
|
+
if not (exclude_fixed and frame.joint.joint_type == "fixed"):
|
|
86
|
+
joint_names.append(frame.joint.name)
|
|
87
|
+
for child in frame.children:
|
|
88
|
+
joint_names.extend(Chain._get_joint_parameter_names(child, exclude_fixed))
|
|
89
|
+
return joint_names
|
|
90
|
+
|
|
91
|
+
def get_joint_parameter_names(self, exclude_fixed: bool = True) -> List[str]:
|
|
92
|
+
"""Get joint parameter names.
|
|
93
|
+
|
|
94
|
+
Parameters
|
|
95
|
+
----------
|
|
96
|
+
exclude_fixed : bool, optional
|
|
97
|
+
Exclude fixed joints, by default True
|
|
98
|
+
|
|
99
|
+
Returns
|
|
100
|
+
-------
|
|
101
|
+
List[str]
|
|
102
|
+
Joint parameter names.
|
|
103
|
+
"""
|
|
104
|
+
assert self._root is not None, "Root frame is None"
|
|
105
|
+
names = self._get_joint_parameter_names(self._root, exclude_fixed)
|
|
106
|
+
return list(sorted(set(names), key=names.index))
|
|
107
|
+
|
|
108
|
+
def add_frame(self, frame: frame.Frame, parent_name: str) -> None:
|
|
109
|
+
parent_frame = self.find_frame(parent_name)
|
|
110
|
+
if parent_frame is not None:
|
|
111
|
+
parent_frame.add_child(frame)
|
|
112
|
+
|
|
113
|
+
@staticmethod
|
|
114
|
+
def _forward_kinematics(
|
|
115
|
+
root: frame.Frame, th_dict: Dict[str, float], world: Optional[transform.Transform] = None
|
|
116
|
+
) -> Dict[str, transform.Transform]:
|
|
117
|
+
world = world or transform.Transform()
|
|
118
|
+
link_transforms = {}
|
|
119
|
+
trans = world * root.get_transform(th_dict.get(root.joint.name, 0.0))
|
|
120
|
+
link_transforms[root.link.name] = trans * root.link.offset
|
|
121
|
+
for child in root.children:
|
|
122
|
+
link_transforms.update(Chain._forward_kinematics(child, th_dict, trans))
|
|
123
|
+
return link_transforms
|
|
124
|
+
|
|
125
|
+
def forward_kinematics(
|
|
126
|
+
self, th: Union[Dict[str, float], List[float]], world: Optional[transform.Transform] = None, **kwargs: Dict
|
|
127
|
+
) -> Dict[str, transform.Transform]:
|
|
128
|
+
"""Forward kinematics.
|
|
129
|
+
|
|
130
|
+
Parameters
|
|
131
|
+
----------
|
|
132
|
+
th : Union[Dict[str, float], List[float]]
|
|
133
|
+
Joint parameters.
|
|
134
|
+
world : Optional[transform.Transform], optional
|
|
135
|
+
World transform, by default None
|
|
136
|
+
|
|
137
|
+
Returns
|
|
138
|
+
-------
|
|
139
|
+
Dict[str, transform.Transform]
|
|
140
|
+
Link transforms.
|
|
141
|
+
"""
|
|
142
|
+
assert self._root is not None, "Root frame is None"
|
|
143
|
+
world = world or transform.Transform()
|
|
144
|
+
if not isinstance(th, dict):
|
|
145
|
+
jn = self.get_joint_parameter_names()
|
|
146
|
+
assert len(jn) == len(th)
|
|
147
|
+
th_dict = dict((j, th[i]) for i, j in enumerate(jn))
|
|
148
|
+
else:
|
|
149
|
+
th_dict = th
|
|
150
|
+
return self._forward_kinematics(self._root, th_dict, world)
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def _visuals_map(root: frame.Frame) -> Dict[str, List[frame.Visual]]:
|
|
154
|
+
vmap = {root.link.name: root.link.visuals}
|
|
155
|
+
for child in root.children:
|
|
156
|
+
vmap.update(Chain._visuals_map(child))
|
|
157
|
+
return vmap
|
|
158
|
+
|
|
159
|
+
def visuals_map(self):
|
|
160
|
+
return self._visuals_map(self._root)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class SerialChain(Chain):
|
|
164
|
+
"""SerialChain is a class that represents a serial kinematic chain."""
|
|
165
|
+
|
|
166
|
+
def __init__(self, chain: Chain, end_frame_name: str, root_frame_name: str = "") -> None:
|
|
167
|
+
assert chain._root is not None, "Chain root frame is None"
|
|
168
|
+
if root_frame_name == "":
|
|
169
|
+
self._root = chain._root
|
|
170
|
+
else:
|
|
171
|
+
self._root = chain.find_frame(root_frame_name)
|
|
172
|
+
if self._root is None:
|
|
173
|
+
raise ValueError("Invalid root frame name %s." % root_frame_name)
|
|
174
|
+
frames = self._generate_serial_chain_recurse(self._root, end_frame_name)
|
|
175
|
+
if frames is None:
|
|
176
|
+
raise ValueError("Invalid end frame name %s." % end_frame_name)
|
|
177
|
+
self._serial_frames = [self._root] + frames
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def _generate_serial_chain_recurse(root_frame: frame.Frame, end_frame_name: str) -> Optional[List[frame.Frame]]:
|
|
181
|
+
for child in root_frame.children:
|
|
182
|
+
if child.name == end_frame_name:
|
|
183
|
+
return [child]
|
|
184
|
+
else:
|
|
185
|
+
frames = SerialChain._generate_serial_chain_recurse(child, end_frame_name)
|
|
186
|
+
if frames is not None:
|
|
187
|
+
return [child] + frames
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
def get_joint_parameter_names(self, exclude_fixed: bool = True) -> List[str]:
|
|
191
|
+
assert self._serial_frames is not None, "Serial chain not initialized."
|
|
192
|
+
names = []
|
|
193
|
+
for f in self._serial_frames:
|
|
194
|
+
if exclude_fixed and f.joint.joint_type == "fixed":
|
|
195
|
+
continue
|
|
196
|
+
names.append(f.joint.name)
|
|
197
|
+
return names
|
|
198
|
+
|
|
199
|
+
def forward_kinematics( # type: ignore[override]
|
|
200
|
+
self,
|
|
201
|
+
th: Union[Dict[str, float], List[float]],
|
|
202
|
+
world: Optional[transform.Transform] = None,
|
|
203
|
+
end_only: bool = True,
|
|
204
|
+
) -> Union[transform.Transform, Dict[str, transform.Transform]]:
|
|
205
|
+
assert self._serial_frames is not None, "Serial chain not initialized."
|
|
206
|
+
if isinstance(th, dict):
|
|
207
|
+
link_transforms = super().forward_kinematics(th, world)
|
|
208
|
+
if end_only:
|
|
209
|
+
return link_transforms[self._serial_frames[-1].link.name]
|
|
210
|
+
else:
|
|
211
|
+
return link_transforms
|
|
212
|
+
world = world or transform.Transform()
|
|
213
|
+
cnt = 0
|
|
214
|
+
link_transforms = {}
|
|
215
|
+
trans = world
|
|
216
|
+
for f in self._serial_frames:
|
|
217
|
+
if f.joint.joint_type != "fixed":
|
|
218
|
+
trans = trans * f.get_transform(th[cnt])
|
|
219
|
+
else:
|
|
220
|
+
trans = trans * f.get_transform()
|
|
221
|
+
link_transforms[f.link.name] = trans * f.link.offset
|
|
222
|
+
if f.joint.joint_type != "fixed":
|
|
223
|
+
cnt += 1
|
|
224
|
+
return link_transforms[self._serial_frames[-1].link.name] if end_only else link_transforms
|
|
225
|
+
|
|
226
|
+
def jacobian(self, th: List[float], end_only: bool = True) -> Union[np.ndarray, Dict[str, np.ndarray]]:
|
|
227
|
+
assert self._serial_frames is not None, "Serial chain not initialized."
|
|
228
|
+
if end_only:
|
|
229
|
+
return jacobian.calc_jacobian(self, th)
|
|
230
|
+
else:
|
|
231
|
+
jacobians = {}
|
|
232
|
+
for serial_frame in self._serial_frames:
|
|
233
|
+
jac = jacobian.calc_jacobian_frames(self, th, link_name=serial_frame.link.name)
|
|
234
|
+
jacobians[serial_frame.link.name] = jac
|
|
235
|
+
return jacobians
|
|
236
|
+
|
|
237
|
+
def inverse_kinematics(self, pose: transform.Transform, initial_state: Optional[np.ndarray] = None) -> np.ndarray:
|
|
238
|
+
return ik.inverse_kinematics(self, pose, initial_state)
|
kinpy/frame.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from typing import Any, Iterator, List, Optional
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import transformations as tf
|
|
5
|
+
|
|
6
|
+
from . import transform
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Visual:
|
|
10
|
+
TYPES = ["box", "cylinder", "sphere", "capsule", "mesh"]
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
offset: Optional[transform.Transform] = None,
|
|
15
|
+
geom_type: Optional[str] = None,
|
|
16
|
+
geom_param: Any = None,
|
|
17
|
+
) -> None:
|
|
18
|
+
self.offset = offset or transform.Transform()
|
|
19
|
+
self.geom_type = geom_type
|
|
20
|
+
self.geom_param = geom_param
|
|
21
|
+
|
|
22
|
+
def __repr__(self) -> str:
|
|
23
|
+
return "Visual(offset={0}, geom_type='{1}', geom_param={2})".format(
|
|
24
|
+
self.offset, self.geom_type, self.geom_param
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Link:
|
|
29
|
+
def __init__(
|
|
30
|
+
self, name: Optional[str] = None, offset: Optional[transform.Transform] = None, visuals: Optional[List] = None
|
|
31
|
+
) -> None:
|
|
32
|
+
self.name = name if name is not None else "none"
|
|
33
|
+
self.offset = offset or transform.Transform()
|
|
34
|
+
self.visuals = visuals or []
|
|
35
|
+
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return "Link(name='{0}', offset={1}, visuals={2})".format(self.name, self.offset, self.visuals)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Joint:
|
|
41
|
+
TYPES = ["fixed", "revolute", "prismatic"]
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
name: Optional[str] = None,
|
|
46
|
+
offset: Optional[transform.Transform] = None,
|
|
47
|
+
joint_type: str = "fixed",
|
|
48
|
+
axis: Optional[List[float]] = None,
|
|
49
|
+
) -> None:
|
|
50
|
+
self.name = name if name is not None else "none"
|
|
51
|
+
self.offset = offset or transform.Transform()
|
|
52
|
+
self.joint_type = joint_type
|
|
53
|
+
if self.joint_type != "fixed" and axis is None:
|
|
54
|
+
self.axis = np.array([0.0, 0.0, 1.0])
|
|
55
|
+
else:
|
|
56
|
+
self.axis = np.array(axis) if axis is not None else np.array([0.0, 0.0, 1.0])
|
|
57
|
+
|
|
58
|
+
def __repr__(self) -> str:
|
|
59
|
+
return "Joint(name='{0}', offset={1}, joint_type='{2}', axis={3})".format(
|
|
60
|
+
self.name, self.offset, self.joint_type, self.axis
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Frame:
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
name: Optional[str] = None,
|
|
68
|
+
link: Optional[Link] = None,
|
|
69
|
+
joint: Optional[Joint] = None,
|
|
70
|
+
children: Optional[List["Frame"]] = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
self.name = "None" if name is None else name
|
|
73
|
+
self.link = link or Link()
|
|
74
|
+
self.joint = joint or Joint()
|
|
75
|
+
self.children = children or []
|
|
76
|
+
|
|
77
|
+
def _ptree(self, indent_width: int = 4) -> str:
|
|
78
|
+
def _inner_ptree(root: Frame, parent: Frame, grandpa: Optional[Frame] = None, indent: str = ""):
|
|
79
|
+
show_str = ""
|
|
80
|
+
if parent.name != root.name:
|
|
81
|
+
show_str += " " + parent.name + ("" if grandpa is None else "\n")
|
|
82
|
+
if not parent.children:
|
|
83
|
+
return show_str
|
|
84
|
+
for child in parent.children[:-1]:
|
|
85
|
+
show_str += indent + "├" + "─" * indent_width
|
|
86
|
+
show_str += _inner_ptree(root, child, parent, indent + "│" + " " * (indent_width + 1))
|
|
87
|
+
if parent.children:
|
|
88
|
+
child = parent.children[-1]
|
|
89
|
+
show_str += indent + "└" + "─" * indent_width
|
|
90
|
+
show_str += _inner_ptree(root, child, parent, indent + " " * (indent_width + 2))
|
|
91
|
+
return show_str
|
|
92
|
+
|
|
93
|
+
show_str = self.name + "\n"
|
|
94
|
+
show_str += _inner_ptree(self, self)
|
|
95
|
+
return show_str
|
|
96
|
+
|
|
97
|
+
def __str__(self) -> str:
|
|
98
|
+
return self._ptree()
|
|
99
|
+
|
|
100
|
+
def add_child(self, child: "Frame") -> None:
|
|
101
|
+
self.children.append(child)
|
|
102
|
+
|
|
103
|
+
def is_end(self) -> bool:
|
|
104
|
+
return len(self.children) == 0
|
|
105
|
+
|
|
106
|
+
def get_transform(self, theta: float = 0.0) -> transform.Transform:
|
|
107
|
+
if self.joint.joint_type == "revolute":
|
|
108
|
+
t = transform.Transform(tf.quaternion_about_axis(theta, self.joint.axis))
|
|
109
|
+
elif self.joint.joint_type == "prismatic":
|
|
110
|
+
t = transform.Transform(pos=theta * self.joint.axis)
|
|
111
|
+
elif self.joint.joint_type == "fixed":
|
|
112
|
+
t = transform.Transform()
|
|
113
|
+
else:
|
|
114
|
+
raise ValueError("Unsupported joint type %s." % self.joint.joint_type)
|
|
115
|
+
return self.joint.offset * t
|
|
116
|
+
|
|
117
|
+
def walk(self) -> Iterator["Frame"]:
|
|
118
|
+
yield self
|
|
119
|
+
for child in self.children:
|
|
120
|
+
yield from child.walk()
|
kinpy/ik.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from typing import Any, Optional
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import scipy.optimize as sco
|
|
5
|
+
|
|
6
|
+
from . import transform
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def inverse_kinematics(
|
|
10
|
+
serial_chain: Any, pose: transform.Transform, initial_state: Optional[np.ndarray] = None
|
|
11
|
+
) -> np.ndarray:
|
|
12
|
+
ndim = len(serial_chain.get_joint_parameter_names())
|
|
13
|
+
if initial_state is None:
|
|
14
|
+
x0 = np.zeros(ndim)
|
|
15
|
+
else:
|
|
16
|
+
x0 = initial_state
|
|
17
|
+
|
|
18
|
+
def object_fn(x):
|
|
19
|
+
tf = serial_chain.forward_kinematics(x)
|
|
20
|
+
obj = np.square(np.linalg.lstsq(pose.matrix(), tf.matrix(), rcond=-1)[0] - np.identity(4)).sum()
|
|
21
|
+
return obj
|
|
22
|
+
|
|
23
|
+
ret = sco.minimize(object_fn, x0, method="BFGS")
|
|
24
|
+
return ret.x
|
kinpy/jacobian.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from typing import Any, List, Optional
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from . import transform
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def calc_jacobian(serial_chain: Any, th: List[float], tool: Optional[transform.Transform] = None) -> np.ndarray:
|
|
9
|
+
tool = tool or transform.Transform()
|
|
10
|
+
ndof = len(th)
|
|
11
|
+
j_fl = np.zeros((6, ndof))
|
|
12
|
+
cur_transform = tool.matrix()
|
|
13
|
+
|
|
14
|
+
cnt = 0
|
|
15
|
+
for f in reversed(serial_chain._serial_frames):
|
|
16
|
+
if f.joint.joint_type == "revolute":
|
|
17
|
+
cnt += 1
|
|
18
|
+
delta = np.dot(f.joint.axis, cur_transform[:3, :3])
|
|
19
|
+
d = np.dot(np.cross(f.joint.axis, cur_transform[:3, 3]), cur_transform[:3, :3])
|
|
20
|
+
j_fl[:, -cnt] = np.hstack((d, delta))
|
|
21
|
+
elif f.joint.joint_type == "prismatic":
|
|
22
|
+
cnt += 1
|
|
23
|
+
j_fl[:3, -cnt] = np.dot(f.joint.axis, cur_transform[:3, :3])
|
|
24
|
+
cur_frame_transform = f.get_transform(th[-cnt]).matrix()
|
|
25
|
+
cur_transform = np.dot(cur_frame_transform, cur_transform)
|
|
26
|
+
|
|
27
|
+
pose = serial_chain.forward_kinematics(th).matrix()
|
|
28
|
+
rotation = pose[:3, :3]
|
|
29
|
+
j_tr = np.zeros((6, 6))
|
|
30
|
+
j_tr[:3, :3] = rotation
|
|
31
|
+
j_tr[3:, 3:] = rotation
|
|
32
|
+
j_w = np.dot(j_tr, j_fl)
|
|
33
|
+
return j_w
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def calc_jacobian_frames(
|
|
37
|
+
serial_chain: Any, th: List[float], link_name: str, tool: Optional[transform.Transform] = None
|
|
38
|
+
) -> np.ndarray:
|
|
39
|
+
tool = tool or transform.Transform()
|
|
40
|
+
ndof = len(th)
|
|
41
|
+
j_fl = np.zeros((6, ndof))
|
|
42
|
+
cur_transform = tool.matrix()
|
|
43
|
+
|
|
44
|
+
# select first num_th movable joints
|
|
45
|
+
serial_frames = []
|
|
46
|
+
num_movable_joints = 0
|
|
47
|
+
for serial_frame in serial_chain._serial_frames:
|
|
48
|
+
serial_frames.append(serial_frame)
|
|
49
|
+
if serial_frame.joint.joint_type != "fixed":
|
|
50
|
+
num_movable_joints += 1
|
|
51
|
+
|
|
52
|
+
if serial_frame.link.name == link_name:
|
|
53
|
+
break # found first n joints
|
|
54
|
+
|
|
55
|
+
cnt = len(th) - num_movable_joints # only first num_th joints
|
|
56
|
+
for f in reversed(serial_frames):
|
|
57
|
+
if f.joint.joint_type == "revolute":
|
|
58
|
+
cnt += 1
|
|
59
|
+
delta = np.dot(f.joint.axis, cur_transform[:3, :3])
|
|
60
|
+
d = np.dot(np.cross(f.joint.axis, cur_transform[:3, 3]), cur_transform[:3, :3])
|
|
61
|
+
j_fl[:, -cnt] = np.hstack((d, delta))
|
|
62
|
+
elif f.joint.joint_type == "prismatic":
|
|
63
|
+
cnt += 1
|
|
64
|
+
j_fl[:3, -cnt] = np.dot(f.joint.axis, cur_transform[:3, :3])
|
|
65
|
+
cur_frame_transform = f.get_transform(th[-cnt]).matrix()
|
|
66
|
+
cur_transform = np.dot(cur_frame_transform, cur_transform)
|
|
67
|
+
|
|
68
|
+
poses = serial_chain.forward_kinematics(th, end_only=False)
|
|
69
|
+
pose = poses[link_name].matrix()
|
|
70
|
+
|
|
71
|
+
rotation = pose[:3, :3]
|
|
72
|
+
j_tr = np.zeros((6, 6))
|
|
73
|
+
j_tr[:3, :3] = rotation
|
|
74
|
+
j_tr[3:, 3:] = rotation
|
|
75
|
+
j_w = np.dot(j_tr, j_fl)
|
|
76
|
+
|
|
77
|
+
return j_w
|
kinpy/mjcf.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import io
|
|
2
|
+
from typing import Dict, Optional, TextIO, Union
|
|
3
|
+
|
|
4
|
+
from . import chain, frame, mjcf_parser, transform
|
|
5
|
+
|
|
6
|
+
JOINT_TYPE_MAP: Dict[str, str] = {"hinge": "revolute", "slide": "prismatic"}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def geoms_to_visuals(geom, base: Optional[transform.Transform] = None):
|
|
10
|
+
base = base or transform.Transform()
|
|
11
|
+
visuals = []
|
|
12
|
+
for g in geom:
|
|
13
|
+
if g.type == "capsule":
|
|
14
|
+
param = (g.size[0], g.fromto)
|
|
15
|
+
elif g.type == "sphere":
|
|
16
|
+
param = g.size[0]
|
|
17
|
+
else:
|
|
18
|
+
raise ValueError("Invalid geometry type %s." % g.type)
|
|
19
|
+
visuals.append(
|
|
20
|
+
frame.Visual(offset=base * transform.Transform(g.quat, g.pos), geom_type=g.type, geom_param=param)
|
|
21
|
+
)
|
|
22
|
+
return visuals
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def body_to_link(body, base: Optional[transform.Transform] = None):
|
|
26
|
+
base = base or transform.Transform()
|
|
27
|
+
return frame.Link(body.name, offset=base * transform.Transform(body.quat, body.pos))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def joint_to_joint(joint, base: Optional[transform.Transform] = None):
|
|
31
|
+
base = base or transform.Transform()
|
|
32
|
+
return frame.Joint(
|
|
33
|
+
joint.name,
|
|
34
|
+
offset=base * transform.Transform(pos=joint.pos),
|
|
35
|
+
joint_type=JOINT_TYPE_MAP[joint.type],
|
|
36
|
+
axis=joint.axis,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def add_composite_joint(root_frame, joints, base: Optional[transform.Transform] = None):
|
|
41
|
+
base = base or transform.Transform()
|
|
42
|
+
if len(joints) > 0:
|
|
43
|
+
root_frame.children = root_frame.children + [
|
|
44
|
+
frame.Frame(link=frame.Link(name=root_frame.link.name + "_child"), joint=joint_to_joint(joints[0], base))
|
|
45
|
+
]
|
|
46
|
+
ret, offset = add_composite_joint(root_frame.children[-1], joints[1:])
|
|
47
|
+
return ret, root_frame.joint.offset * offset
|
|
48
|
+
else:
|
|
49
|
+
return root_frame, root_frame.joint.offset
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _build_chain_recurse(root_frame, root_body):
|
|
53
|
+
base = root_frame.link.offset
|
|
54
|
+
cur_frame, cur_base = add_composite_joint(root_frame, root_body.joint, base)
|
|
55
|
+
jbase = cur_base.inverse() * base
|
|
56
|
+
if len(root_body.joint) > 0:
|
|
57
|
+
cur_frame.link.visuals = geoms_to_visuals(root_body.geom, jbase)
|
|
58
|
+
else:
|
|
59
|
+
cur_frame.link.visuals = geoms_to_visuals(root_body.geom)
|
|
60
|
+
for b in root_body.body:
|
|
61
|
+
cur_frame.children = cur_frame.children + [frame.Frame()]
|
|
62
|
+
next_frame = cur_frame.children[-1]
|
|
63
|
+
next_frame.name = b.name + "_frame"
|
|
64
|
+
next_frame.link = body_to_link(b, jbase)
|
|
65
|
+
_build_chain_recurse(next_frame, b)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def build_chain_from_mjcf(data: Union[str, TextIO]) -> chain.Chain:
|
|
69
|
+
"""
|
|
70
|
+
Build a Chain object from MJCF data.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
data : str or TextIO
|
|
75
|
+
MJCF string data or file object.
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
-------
|
|
79
|
+
chain.Chain
|
|
80
|
+
Chain object created from MJCF.
|
|
81
|
+
"""
|
|
82
|
+
if isinstance(data, io.TextIOBase):
|
|
83
|
+
data = data.read()
|
|
84
|
+
model = mjcf_parser.from_xml_string(data)
|
|
85
|
+
root_body = model.worldbody.body[0]
|
|
86
|
+
root_frame = frame.Frame(root_body.name + "_frame", link=body_to_link(root_body), joint=frame.Joint())
|
|
87
|
+
_build_chain_recurse(root_frame, root_body)
|
|
88
|
+
return chain.Chain(root_frame)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build_serial_chain_from_mjcf(
|
|
92
|
+
data: Union[str, TextIO], end_link_name: str, root_link_name: str = ""
|
|
93
|
+
) -> chain.SerialChain:
|
|
94
|
+
"""
|
|
95
|
+
Build a SerialChain object from MJCF data.
|
|
96
|
+
|
|
97
|
+
Parameters
|
|
98
|
+
----------
|
|
99
|
+
data : str
|
|
100
|
+
MJCF string data.
|
|
101
|
+
end_link_name : str
|
|
102
|
+
The name of the link that is the end effector.
|
|
103
|
+
root_link_name : str, optional
|
|
104
|
+
The name of the root link.
|
|
105
|
+
|
|
106
|
+
Returns
|
|
107
|
+
-------
|
|
108
|
+
chain.SerialChain
|
|
109
|
+
SerialChain object created from MJCF.
|
|
110
|
+
"""
|
|
111
|
+
if isinstance(data, io.TextIOBase):
|
|
112
|
+
data = data.read()
|
|
113
|
+
mjcf_chain = build_chain_from_mjcf(data)
|
|
114
|
+
return chain.SerialChain(
|
|
115
|
+
mjcf_chain, end_link_name + "_frame", "" if root_link_name == "" else root_link_name + "_frame"
|
|
116
|
+
)
|