teleopro-core 0.1.0__tar.gz

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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ include LICENSE README.md package.xml resource/teleopro_core
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: teleopro_core
3
+ Version: 0.1.0
4
+ Summary: Device- and robot-agnostic teleoperation mapping, no ROS required.
5
+ Home-page: https://github.com/ShifeiDuan/teleopro
6
+ Maintainer: Shifei Duan
7
+ Maintainer-email: sdua078@aucklanduni.ac.nz
8
+ License: Apache-2.0
9
+ Project-URL: Source, https://github.com/ShifeiDuan/teleopro
10
+ Project-URL: Issues, https://github.com/ShifeiDuan/teleopro/issues
11
+ Keywords: teleoperation,robotics,ros2,xr,spacemouse
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: home-page
29
+ Dynamic: keywords
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: maintainer
33
+ Dynamic: maintainer-email
34
+ Dynamic: project-url
35
+ Dynamic: provides-extra
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # teleopro_core
41
+
42
+ Teleoperate any robot with any input device, in pure Python (numpy only, no
43
+ ROS). It turns the motion of a device (XR headset, tracker, mocap, ...) into a
44
+ target pose for the robot, with clutch, speed limits and input-loss handling.
45
+
46
+ ROS users: use the `teleopro_ros` package, which wraps this library with TF.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install "git+https://github.com/ShifeiDuan/teleopro#subdirectory=teleopro_core"
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ ```python
57
+ import time
58
+ from teleopro_core import Teleop, as_pos_quat
59
+
60
+ teleop = Teleop(translation_scale=0.5, max_lin_vel=0.1)
61
+
62
+ teleop.engage() # e.g. when a button is pressed
63
+ while True:
64
+ device_pose = my_device.get_pose() # ((x, y, z), (qx, qy, qz, qw)) or 4x4, None if not tracked
65
+ robot_pose = my_robot.get_tcp_pose() # same formats, in the robot base frame
66
+ target = teleop.update(time.monotonic(), device_pose, robot_pose)
67
+ if target is not None:
68
+ my_robot.move_to(*as_pos_quat(target))
69
+ time.sleep(0.01)
70
+ ```
71
+
72
+ - On `engage()` the target starts at the current robot pose, then follows the
73
+ device's motion since that moment. `disengage()` holds it still (clutch).
74
+ - If the device is not tracked (`None`) or its `input_stamp` is older than
75
+ `input_timeout`, the target holds; when tracking returns it continues from
76
+ where it stopped, without jumping.
77
+ - Before the first engage, `update()` returns the robot pose latched once.
78
+
79
+ Velocity devices (keyboard, SpaceMouse) use `update_twist()` instead:
80
+
81
+ ```python
82
+ teleop = Teleop(twist_frame='tool') # or 'base'
83
+ target = teleop.update_twist(time.monotonic(), ((vx, vy, vz), (wx, wy, wz)), robot_pose)
84
+ ```
85
+
86
+ ## Parameters
87
+
88
+ | Parameter | Default | Meaning |
89
+ |---|---|---|
90
+ | `align_rpy` | `(0, 0, 0)` | Rotation from device axes to robot axes |
91
+ | `translation_scale`, `rotation_scale` | `1.0` | Motion scaling |
92
+ | `max_lin_vel`, `max_ang_vel` | `0.5`, `1.0` | Target speed limits (m/s, rad/s), 0 = off |
93
+ | `dof_mask` | `(1, 1, 1, 1, 1, 1)` | `[x, y, z, roll, pitch, yaw]`; 0 freezes a DoF |
94
+ | `workspace_min`, `workspace_max` | `None` | `[x, y, z]` box the target stays in |
95
+ | `input_timeout` | `0.2` | Seconds before a stale `input_stamp` counts as lost |
96
+ | `twist_frame` | `'base'` | `'base'` or `'tool'`, frame of the twist in `update_twist()` |
97
+ | `logger` | `logging` | Anything with `.debug()` / `.info()` / `.warning()` |
98
+
99
+ ## License
100
+
101
+ Apache-2.0
@@ -0,0 +1,62 @@
1
+ # teleopro_core
2
+
3
+ Teleoperate any robot with any input device, in pure Python (numpy only, no
4
+ ROS). It turns the motion of a device (XR headset, tracker, mocap, ...) into a
5
+ target pose for the robot, with clutch, speed limits and input-loss handling.
6
+
7
+ ROS users: use the `teleopro_ros` package, which wraps this library with TF.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install "git+https://github.com/ShifeiDuan/teleopro#subdirectory=teleopro_core"
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ import time
19
+ from teleopro_core import Teleop, as_pos_quat
20
+
21
+ teleop = Teleop(translation_scale=0.5, max_lin_vel=0.1)
22
+
23
+ teleop.engage() # e.g. when a button is pressed
24
+ while True:
25
+ device_pose = my_device.get_pose() # ((x, y, z), (qx, qy, qz, qw)) or 4x4, None if not tracked
26
+ robot_pose = my_robot.get_tcp_pose() # same formats, in the robot base frame
27
+ target = teleop.update(time.monotonic(), device_pose, robot_pose)
28
+ if target is not None:
29
+ my_robot.move_to(*as_pos_quat(target))
30
+ time.sleep(0.01)
31
+ ```
32
+
33
+ - On `engage()` the target starts at the current robot pose, then follows the
34
+ device's motion since that moment. `disengage()` holds it still (clutch).
35
+ - If the device is not tracked (`None`) or its `input_stamp` is older than
36
+ `input_timeout`, the target holds; when tracking returns it continues from
37
+ where it stopped, without jumping.
38
+ - Before the first engage, `update()` returns the robot pose latched once.
39
+
40
+ Velocity devices (keyboard, SpaceMouse) use `update_twist()` instead:
41
+
42
+ ```python
43
+ teleop = Teleop(twist_frame='tool') # or 'base'
44
+ target = teleop.update_twist(time.monotonic(), ((vx, vy, vz), (wx, wy, wz)), robot_pose)
45
+ ```
46
+
47
+ ## Parameters
48
+
49
+ | Parameter | Default | Meaning |
50
+ |---|---|---|
51
+ | `align_rpy` | `(0, 0, 0)` | Rotation from device axes to robot axes |
52
+ | `translation_scale`, `rotation_scale` | `1.0` | Motion scaling |
53
+ | `max_lin_vel`, `max_ang_vel` | `0.5`, `1.0` | Target speed limits (m/s, rad/s), 0 = off |
54
+ | `dof_mask` | `(1, 1, 1, 1, 1, 1)` | `[x, y, z, roll, pitch, yaw]`; 0 freezes a DoF |
55
+ | `workspace_min`, `workspace_max` | `None` | `[x, y, z]` box the target stays in |
56
+ | `input_timeout` | `0.2` | Seconds before a stale `input_stamp` counts as lost |
57
+ | `twist_frame` | `'base'` | `'base'` or `'tool'`, frame of the twist in `update_twist()` |
58
+ | `logger` | `logging` | Anything with `.debug()` / `.info()` / `.warning()` |
59
+
60
+ ## License
61
+
62
+ Apache-2.0
@@ -0,0 +1,20 @@
1
+ <?xml version="1.0"?>
2
+ <?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
3
+ <package format="3">
4
+ <name>teleopro_core</name>
5
+ <version>0.1.0</version>
6
+ <description>
7
+ Device- and robot-agnostic teleoperation mapping in pure Python (numpy only).
8
+ Usable with or without ROS.
9
+ </description>
10
+ <maintainer email="sdua078@aucklanduni.ac.nz">Shifei Duan</maintainer>
11
+ <license>Apache-2.0</license>
12
+
13
+ <exec_depend>python3-numpy</exec_depend>
14
+
15
+ <test_depend>python3-pytest</test_depend>
16
+
17
+ <export>
18
+ <build_type>ament_python</build_type>
19
+ </export>
20
+ </package>
File without changes
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,47 @@
1
+ import os
2
+
3
+ from setuptools import find_packages, setup
4
+
5
+ package_name = 'teleopro_core'
6
+
7
+ # colcon --symlink-install runs setup.py from the build directory
8
+ readme = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'README.md')
9
+ long_description = ''
10
+ if os.path.exists(readme):
11
+ with open(readme, encoding='utf-8') as f:
12
+ long_description = f.read()
13
+
14
+ setup(
15
+ name=package_name,
16
+ version='0.1.0',
17
+ packages=find_packages(exclude=['test']),
18
+ data_files=[
19
+ ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
20
+ ('share/' + package_name, ['package.xml']),
21
+ ],
22
+ install_requires=['numpy'],
23
+ python_requires='>=3.8',
24
+ zip_safe=True,
25
+ maintainer='Shifei Duan',
26
+ maintainer_email='sdua078@aucklanduni.ac.nz',
27
+ description='Device- and robot-agnostic teleoperation mapping, no ROS required.',
28
+ long_description=long_description,
29
+ long_description_content_type='text/markdown',
30
+ license='Apache-2.0',
31
+ url='https://github.com/ShifeiDuan/teleopro',
32
+ project_urls={
33
+ 'Source': 'https://github.com/ShifeiDuan/teleopro',
34
+ 'Issues': 'https://github.com/ShifeiDuan/teleopro/issues',
35
+ },
36
+ keywords=['teleoperation', 'robotics', 'ros2', 'xr', 'spacemouse'],
37
+ classifiers=[
38
+ 'Development Status :: 3 - Alpha',
39
+ 'Intended Audience :: Developers',
40
+ 'Intended Audience :: Science/Research',
41
+ 'Operating System :: OS Independent',
42
+ 'Programming Language :: Python :: 3',
43
+ 'Topic :: Scientific/Engineering',
44
+ 'Topic :: Software Development :: Libraries :: Python Modules',
45
+ ],
46
+ extras_require={'test': ['pytest']},
47
+ )
@@ -0,0 +1,6 @@
1
+ """Teleoperation mapping for any device and robot."""
2
+
3
+ from teleopro_core.mapping import TeleopMapper
4
+ from teleopro_core.teleop import as_matrix, as_pos_quat, Teleop
5
+
6
+ __all__ = ['Teleop', 'TeleopMapper', 'as_matrix', 'as_pos_quat']
@@ -0,0 +1,150 @@
1
+ """Mapping from input pose or velocity to a robot target pose."""
2
+
3
+ import numpy as np
4
+
5
+ from teleopro_core.transforms import make_transform, matrix_to_rotvec, rotvec_to_matrix
6
+
7
+ TWIST_FRAMES = ('base', 'tool')
8
+
9
+
10
+ class TeleopMapper:
11
+ """Maps input motion onto a robot target pose.
12
+
13
+ Pose input applies the input motion since engage to the reference pose:
14
+
15
+ p = p_ref + s_t * R_align * (p_in - p_in0)
16
+ R = R_align * dR * R_align^T * R_ref, dR = R_in * R_in0^T
17
+
18
+ Twist input integrates the velocity, expressed in the robot base or tool frame.
19
+
20
+ Args:
21
+ align: 3x3 rotation of the input axes in the robot base.
22
+ translation_scale: Translation scale factor.
23
+ rotation_scale: Rotation scale factor.
24
+ dof_mask: [x, y, z, roll, pitch, yaw], 0 locks the axis.
25
+ max_lin_vel: Linear velocity limit in m/s, 0 for none.
26
+ max_ang_vel: Angular velocity limit in rad/s, 0 for none.
27
+ workspace_min: Lower position bound [x, y, z], or None.
28
+ workspace_max: Upper position bound [x, y, z], or None.
29
+ """
30
+
31
+ def __init__(self, align=None, translation_scale=1.0, rotation_scale=1.0,
32
+ dof_mask=(1, 1, 1, 1, 1, 1), max_lin_vel=0.0, max_ang_vel=0.0,
33
+ workspace_min=None, workspace_max=None):
34
+ if len(dof_mask) != 6:
35
+ raise ValueError('dof_mask must have 6 entries [x, y, z, roll, pitch, yaw]')
36
+ self.align = np.eye(3) if align is None else np.asarray(align, dtype=float)
37
+ self.translation_scale = float(translation_scale)
38
+ self.rotation_scale = float(rotation_scale)
39
+ self.dof_mask = np.asarray(dof_mask, dtype=float)
40
+ self.max_lin_vel = float(max_lin_vel)
41
+ self.max_ang_vel = float(max_ang_vel)
42
+ self.workspace_min = None if workspace_min is None else np.asarray(workspace_min, float)
43
+ self.workspace_max = None if workspace_max is None else np.asarray(workspace_max, float)
44
+
45
+ self._input_ref = None
46
+ self._target_ref = None
47
+ self._last_target = None
48
+
49
+ @property
50
+ def engaged(self):
51
+ return self._target_ref is not None
52
+
53
+ @property
54
+ def last_target(self):
55
+ return None if self._last_target is None else self._last_target.copy()
56
+
57
+ def engage(self, T_input, T_target_ref):
58
+ """Set the reference poses.
59
+
60
+ Args:
61
+ T_input: 4x4 input pose in the input base, or None for twist input.
62
+ T_target_ref: 4x4 starting target pose in the robot base.
63
+ """
64
+ self._input_ref = None if T_input is None else np.array(T_input, dtype=float)
65
+ self._target_ref = np.array(T_target_ref, dtype=float)
66
+ self._last_target = self._target_ref.copy()
67
+
68
+ def disengage(self):
69
+ self._input_ref = None
70
+ self._target_ref = None
71
+
72
+ def update(self, T_input, dt):
73
+ """Compute the target pose from an input pose.
74
+
75
+ Args:
76
+ T_input: 4x4 input pose in the input base.
77
+ dt: Time since the last update in seconds.
78
+
79
+ Returns:
80
+ 4x4 target pose in the robot base.
81
+ """
82
+ if self._input_ref is None:
83
+ raise RuntimeError('update() called without an input reference')
84
+ T_in = np.asarray(T_input, dtype=float)
85
+ T0 = self._input_ref
86
+ R_a = self.align
87
+ dp = self.translation_scale * (R_a @ (T_in[:3, 3] - T0[:3, 3]))
88
+ # Rotation vector in robot base
89
+ w = self.rotation_scale * (R_a @ matrix_to_rotvec(T_in[:3, :3] @ T0[:3, :3].T))
90
+ dp *= self.dof_mask[:3]
91
+ w *= self.dof_mask[3:]
92
+ T_desired = make_transform(rotvec_to_matrix(w) @ self._target_ref[:3, :3],
93
+ self._target_ref[:3, 3] + dp)
94
+ return self._finish(T_desired, dt)
95
+
96
+ def integrate(self, linear, angular, dt, frame='base'):
97
+ """Compute the target pose from an input velocity.
98
+
99
+ Args:
100
+ linear: Linear velocity [x, y, z] in m/s.
101
+ angular: Angular velocity [x, y, z] in rad/s.
102
+ dt: Time since the last update in seconds.
103
+ frame: 'base' or 'tool', the frame the velocity is expressed in.
104
+
105
+ Returns:
106
+ 4x4 target pose in the robot base.
107
+ """
108
+ if not self.engaged:
109
+ raise RuntimeError('integrate() called while not engaged')
110
+ if frame not in TWIST_FRAMES:
111
+ raise ValueError(f'frame must be one of {TWIST_FRAMES}, got {frame!r}')
112
+ T_prev = self._last_target
113
+ v = self.translation_scale * (self.align @ np.asarray(linear, dtype=float))
114
+ w = self.rotation_scale * (self.align @ np.asarray(angular, dtype=float))
115
+ if frame == 'tool':
116
+ v = T_prev[:3, :3] @ v
117
+ w = T_prev[:3, :3] @ w
118
+ v *= self.dof_mask[:3]
119
+ w *= self.dof_mask[3:]
120
+ T_desired = make_transform(rotvec_to_matrix(w * dt) @ T_prev[:3, :3],
121
+ T_prev[:3, 3] + v * dt)
122
+ return self._finish(T_desired, dt)
123
+
124
+ def _finish(self, T_desired, dt):
125
+ if self.workspace_min is not None:
126
+ T_desired[:3, 3] = np.maximum(T_desired[:3, 3], self.workspace_min)
127
+ if self.workspace_max is not None:
128
+ T_desired[:3, 3] = np.minimum(T_desired[:3, 3], self.workspace_max)
129
+ T_out = self._limit_rate(self._last_target, T_desired, dt)
130
+ self._last_target = T_out
131
+ return T_out.copy()
132
+
133
+ def _limit_rate(self, T_prev, T_next, dt):
134
+ if dt <= 0.0:
135
+ return T_next
136
+ p_prev, p_next = T_prev[:3, 3], T_next[:3, 3]
137
+ dp = p_next - p_prev
138
+ if self.max_lin_vel > 0.0:
139
+ max_step = self.max_lin_vel * dt
140
+ n = np.linalg.norm(dp)
141
+ if n > max_step:
142
+ dp *= max_step / n
143
+ R = T_next[:3, :3]
144
+ if self.max_ang_vel > 0.0:
145
+ w = matrix_to_rotvec(T_next[:3, :3] @ T_prev[:3, :3].T)
146
+ max_step = self.max_ang_vel * dt
147
+ n = np.linalg.norm(w)
148
+ if n > max_step:
149
+ R = rotvec_to_matrix(w * max_step / n) @ T_prev[:3, :3]
150
+ return make_transform(R, p_prev + dp)
@@ -0,0 +1,186 @@
1
+ """Teleoperation session with engage, input loss and re-anchoring."""
2
+
3
+ import logging
4
+
5
+ import numpy as np
6
+
7
+ from teleopro_core.mapping import TeleopMapper, TWIST_FRAMES
8
+ from teleopro_core.transforms import make_transform, matrix_to_quat, quat_to_matrix, rpy_to_matrix
9
+
10
+
11
+ def as_matrix(pose):
12
+ """Convert a pose to a 4x4 matrix.
13
+
14
+ Args:
15
+ pose: 4x4 matrix or ((x, y, z), (qx, qy, qz, qw)).
16
+ """
17
+ if isinstance(pose, np.ndarray) and pose.shape == (4, 4):
18
+ return pose.astype(float)
19
+ xyz, quat = pose
20
+ return make_transform(quat_to_matrix(quat), xyz)
21
+
22
+
23
+ def as_pos_quat(T):
24
+ """Convert a 4x4 matrix to ((x, y, z), (qx, qy, qz, qw))."""
25
+ return tuple(float(v) for v in T[:3, 3]), tuple(float(v) for v in matrix_to_quat(T[:3, :3]))
26
+
27
+
28
+ class Teleop:
29
+ """Teleoperation session.
30
+
31
+ Args:
32
+ align_rpy: Rotation of the input axes in the robot base (roll, pitch, yaw).
33
+ translation_scale: Translation scale factor.
34
+ rotation_scale: Rotation scale factor.
35
+ max_lin_vel: Linear velocity limit in m/s, 0 for none.
36
+ max_ang_vel: Angular velocity limit in rad/s, 0 for none.
37
+ dof_mask: [x, y, z, roll, pitch, yaw], 0 locks the axis.
38
+ workspace_min: Lower position bound [x, y, z], or None.
39
+ workspace_max: Upper position bound [x, y, z], or None.
40
+ input_timeout: Input older than this many seconds is treated as lost.
41
+ twist_frame: 'base' or 'tool', the frame twist input is expressed in.
42
+ logger: Logger with debug(), info() and warning(). Defaults to logging.
43
+ """
44
+
45
+ def __init__(self, align_rpy=(0.0, 0.0, 0.0), translation_scale=1.0,
46
+ rotation_scale=1.0, max_lin_vel=0.5, max_ang_vel=1.0,
47
+ dof_mask=(1, 1, 1, 1, 1, 1), workspace_min=None, workspace_max=None,
48
+ input_timeout=0.2, twist_frame='base', logger=None):
49
+ if twist_frame not in TWIST_FRAMES:
50
+ raise ValueError(f'twist_frame must be one of {TWIST_FRAMES}, got {twist_frame!r}')
51
+ self.mapper = TeleopMapper(
52
+ align=rpy_to_matrix(*align_rpy),
53
+ translation_scale=translation_scale,
54
+ rotation_scale=rotation_scale,
55
+ dof_mask=dof_mask,
56
+ max_lin_vel=max_lin_vel,
57
+ max_ang_vel=max_ang_vel,
58
+ workspace_min=workspace_min,
59
+ workspace_max=workspace_max,
60
+ )
61
+ self.input_timeout = float(input_timeout)
62
+ self.twist_frame = twist_frame
63
+ self.log = logger if logger is not None else logging.getLogger('teleopro_core')
64
+
65
+ self._want_engaged = False
66
+ self._input_stale = False
67
+ self._needs_reanchor = False
68
+ self._waiting_logged = False
69
+ self._last_lost_log = None
70
+ self._hold_pose = None
71
+ self._last_now = None
72
+
73
+ @property
74
+ def engaged(self):
75
+ return self.mapper.engaged
76
+
77
+ @property
78
+ def needs_robot_pose(self):
79
+ """Whether the next update() uses robot_pose."""
80
+ if self.mapper.engaged:
81
+ return False
82
+ return self._want_engaged or self._hold_pose is None
83
+
84
+ def engage(self):
85
+ """Start following the input."""
86
+ self._want_engaged = True
87
+
88
+ def disengage(self):
89
+ """Stop following the input and hold the target."""
90
+ self._want_engaged = False
91
+ if self.mapper.engaged:
92
+ self._hold_pose = self.mapper.last_target
93
+ self.mapper.disengage()
94
+ self.log.info('Teleop disengaged')
95
+
96
+ def update(self, now, input_pose=None, robot_pose=None, input_stamp=None):
97
+ """Advance one step with pose input.
98
+
99
+ Args:
100
+ now: Current time in seconds.
101
+ input_pose: Input pose in the input base, or None if not tracked.
102
+ robot_pose: Current robot pose in the robot base.
103
+ input_stamp: Time of input_pose in seconds, or None.
104
+
105
+ Returns:
106
+ 4x4 target pose in the robot base, or None if no robot pose yet.
107
+ """
108
+ dt = self._step_time(now)
109
+ T_in = None if input_pose is None else as_matrix(input_pose)
110
+ T_robot = None if robot_pose is None else as_matrix(robot_pose)
111
+
112
+ stale = T_in is None or self._is_stale(now, input_stamp)
113
+ if stale != self._input_stale:
114
+ self._input_stale = stale
115
+ if stale and self.mapper.engaged:
116
+ self._needs_reanchor = True
117
+ # Throttled, tracking can flicker
118
+ if self._last_lost_log is None or now - self._last_lost_log >= 5.0:
119
+ self.log.warning('Input lost, holding target')
120
+ self._last_lost_log = now
121
+
122
+ if self._want_engaged and not stale:
123
+ if not self.mapper.engaged:
124
+ self._try_engage(T_in, T_robot)
125
+ elif self._needs_reanchor:
126
+ # Reset references after input loss
127
+ self.mapper.engage(T_in, self.mapper.last_target)
128
+ self._needs_reanchor = False
129
+ self.log.debug('Input back, re-anchored')
130
+ else:
131
+ return self.mapper.update(T_in, dt)
132
+
133
+ if self.mapper.engaged:
134
+ return self.mapper.last_target
135
+ return self._hold(T_robot)
136
+
137
+ def update_twist(self, now, twist=None, robot_pose=None, twist_stamp=None):
138
+ """Advance one step with twist input.
139
+
140
+ Args:
141
+ now: Current time in seconds.
142
+ twist: ((vx, vy, vz), (wx, wy, wz)) in m/s and rad/s, or None.
143
+ robot_pose: Current robot pose in the robot base.
144
+ twist_stamp: Time of twist in seconds, or None.
145
+
146
+ Returns:
147
+ 4x4 target pose in the robot base, or None if no robot pose yet.
148
+ """
149
+ dt = self._step_time(now)
150
+ T_robot = None if robot_pose is None else as_matrix(robot_pose)
151
+
152
+ if self._want_engaged and not self.mapper.engaged:
153
+ self._try_engage(None, T_robot)
154
+
155
+ if self.mapper.engaged:
156
+ # Stop when the twist is missing or stale
157
+ if twist is None or self._is_stale(now, twist_stamp):
158
+ twist = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
159
+ linear, angular = twist
160
+ return self.mapper.integrate(linear, angular, dt, self.twist_frame)
161
+ return self._hold(T_robot)
162
+
163
+ def _step_time(self, now):
164
+ dt = 0.0 if self._last_now is None else now - self._last_now
165
+ self._last_now = now
166
+ return dt
167
+
168
+ def _is_stale(self, now, stamp):
169
+ return (stamp is not None and self.input_timeout > 0.0
170
+ and now - stamp > self.input_timeout)
171
+
172
+ def _try_engage(self, T_in, T_robot):
173
+ if T_robot is None:
174
+ if not self._waiting_logged:
175
+ self.log.warning('Waiting for robot pose to engage')
176
+ self._waiting_logged = True
177
+ return
178
+ self.mapper.engage(T_in, T_robot)
179
+ self._waiting_logged = False
180
+ self.log.info('Teleop engaged')
181
+
182
+ def _hold(self, T_robot):
183
+ # Hold the first robot pose until engaged
184
+ if self._hold_pose is None and T_robot is not None:
185
+ self._hold_pose = T_robot.copy()
186
+ return None if self._hold_pose is None else self._hold_pose.copy()
@@ -0,0 +1,87 @@
1
+ """SE(3) helpers. Quaternions are (x, y, z, w)."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def quat_to_matrix(q):
7
+ x, y, z, w = q
8
+ n = x * x + y * y + z * z + w * w
9
+ if n < 1e-12:
10
+ return np.eye(3)
11
+ s = 2.0 / n
12
+ return np.array([
13
+ [1 - s * (y * y + z * z), s * (x * y - z * w), s * (x * z + y * w)],
14
+ [s * (x * y + z * w), 1 - s * (x * x + z * z), s * (y * z - x * w)],
15
+ [s * (x * z - y * w), s * (y * z + x * w), 1 - s * (x * x + y * y)],
16
+ ])
17
+
18
+
19
+ def matrix_to_quat(R):
20
+ tr = np.trace(R)
21
+ if tr > 0:
22
+ s = 2.0 * np.sqrt(tr + 1.0)
23
+ w = 0.25 * s
24
+ x = (R[2, 1] - R[1, 2]) / s
25
+ y = (R[0, 2] - R[2, 0]) / s
26
+ z = (R[1, 0] - R[0, 1]) / s
27
+ elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
28
+ s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])
29
+ w = (R[2, 1] - R[1, 2]) / s
30
+ x = 0.25 * s
31
+ y = (R[0, 1] + R[1, 0]) / s
32
+ z = (R[0, 2] + R[2, 0]) / s
33
+ elif R[1, 1] > R[2, 2]:
34
+ s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])
35
+ w = (R[0, 2] - R[2, 0]) / s
36
+ x = (R[0, 1] + R[1, 0]) / s
37
+ y = 0.25 * s
38
+ z = (R[1, 2] + R[2, 1]) / s
39
+ else:
40
+ s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])
41
+ w = (R[1, 0] - R[0, 1]) / s
42
+ x = (R[0, 2] + R[2, 0]) / s
43
+ y = (R[1, 2] + R[2, 1]) / s
44
+ z = 0.25 * s
45
+ q = np.array([x, y, z, w])
46
+ return q / np.linalg.norm(q)
47
+
48
+
49
+ def rpy_to_matrix(roll, pitch, yaw):
50
+ """Fixed-axis roll, pitch, yaw to rotation matrix (URDF convention)."""
51
+ cr, sr = np.cos(roll), np.sin(roll)
52
+ cp, sp = np.cos(pitch), np.sin(pitch)
53
+ cy, sy = np.cos(yaw), np.sin(yaw)
54
+ return np.array([
55
+ [cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
56
+ [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
57
+ [-sp, cp * sr, cp * cr],
58
+ ])
59
+
60
+
61
+ def rotvec_to_matrix(v):
62
+ theta = np.linalg.norm(v)
63
+ if theta < 1e-12:
64
+ return np.eye(3)
65
+ k = v / theta
66
+ K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
67
+ return np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K)
68
+
69
+
70
+ def matrix_to_rotvec(R):
71
+ q = matrix_to_quat(R)
72
+ if q[3] < 0:
73
+ q = -q
74
+ s = np.linalg.norm(q[:3])
75
+ if s < 1e-12:
76
+ return np.zeros(3)
77
+ theta = 2.0 * np.arctan2(s, q[3])
78
+ return q[:3] / s * theta
79
+
80
+
81
+ def make_transform(R=None, p=None):
82
+ T = np.eye(4)
83
+ if R is not None:
84
+ T[:3, :3] = R
85
+ if p is not None:
86
+ T[:3, 3] = p
87
+ return T
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: teleopro_core
3
+ Version: 0.1.0
4
+ Summary: Device- and robot-agnostic teleoperation mapping, no ROS required.
5
+ Home-page: https://github.com/ShifeiDuan/teleopro
6
+ Maintainer: Shifei Duan
7
+ Maintainer-email: sdua078@aucklanduni.ac.nz
8
+ License: Apache-2.0
9
+ Project-URL: Source, https://github.com/ShifeiDuan/teleopro
10
+ Project-URL: Issues, https://github.com/ShifeiDuan/teleopro/issues
11
+ Keywords: teleoperation,robotics,ros2,xr,spacemouse
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: home-page
29
+ Dynamic: keywords
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: maintainer
33
+ Dynamic: maintainer-email
34
+ Dynamic: project-url
35
+ Dynamic: provides-extra
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # teleopro_core
41
+
42
+ Teleoperate any robot with any input device, in pure Python (numpy only, no
43
+ ROS). It turns the motion of a device (XR headset, tracker, mocap, ...) into a
44
+ target pose for the robot, with clutch, speed limits and input-loss handling.
45
+
46
+ ROS users: use the `teleopro_ros` package, which wraps this library with TF.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install "git+https://github.com/ShifeiDuan/teleopro#subdirectory=teleopro_core"
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ ```python
57
+ import time
58
+ from teleopro_core import Teleop, as_pos_quat
59
+
60
+ teleop = Teleop(translation_scale=0.5, max_lin_vel=0.1)
61
+
62
+ teleop.engage() # e.g. when a button is pressed
63
+ while True:
64
+ device_pose = my_device.get_pose() # ((x, y, z), (qx, qy, qz, qw)) or 4x4, None if not tracked
65
+ robot_pose = my_robot.get_tcp_pose() # same formats, in the robot base frame
66
+ target = teleop.update(time.monotonic(), device_pose, robot_pose)
67
+ if target is not None:
68
+ my_robot.move_to(*as_pos_quat(target))
69
+ time.sleep(0.01)
70
+ ```
71
+
72
+ - On `engage()` the target starts at the current robot pose, then follows the
73
+ device's motion since that moment. `disengage()` holds it still (clutch).
74
+ - If the device is not tracked (`None`) or its `input_stamp` is older than
75
+ `input_timeout`, the target holds; when tracking returns it continues from
76
+ where it stopped, without jumping.
77
+ - Before the first engage, `update()` returns the robot pose latched once.
78
+
79
+ Velocity devices (keyboard, SpaceMouse) use `update_twist()` instead:
80
+
81
+ ```python
82
+ teleop = Teleop(twist_frame='tool') # or 'base'
83
+ target = teleop.update_twist(time.monotonic(), ((vx, vy, vz), (wx, wy, wz)), robot_pose)
84
+ ```
85
+
86
+ ## Parameters
87
+
88
+ | Parameter | Default | Meaning |
89
+ |---|---|---|
90
+ | `align_rpy` | `(0, 0, 0)` | Rotation from device axes to robot axes |
91
+ | `translation_scale`, `rotation_scale` | `1.0` | Motion scaling |
92
+ | `max_lin_vel`, `max_ang_vel` | `0.5`, `1.0` | Target speed limits (m/s, rad/s), 0 = off |
93
+ | `dof_mask` | `(1, 1, 1, 1, 1, 1)` | `[x, y, z, roll, pitch, yaw]`; 0 freezes a DoF |
94
+ | `workspace_min`, `workspace_max` | `None` | `[x, y, z]` box the target stays in |
95
+ | `input_timeout` | `0.2` | Seconds before a stale `input_stamp` counts as lost |
96
+ | `twist_frame` | `'base'` | `'base'` or `'tool'`, frame of the twist in `update_twist()` |
97
+ | `logger` | `logging` | Anything with `.debug()` / `.info()` / `.warning()` |
98
+
99
+ ## License
100
+
101
+ Apache-2.0
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ package.xml
5
+ setup.py
6
+ resource/teleopro_core
7
+ teleopro_core/__init__.py
8
+ teleopro_core/mapping.py
9
+ teleopro_core/teleop.py
10
+ teleopro_core/transforms.py
11
+ teleopro_core.egg-info/PKG-INFO
12
+ teleopro_core.egg-info/SOURCES.txt
13
+ teleopro_core.egg-info/dependency_links.txt
14
+ teleopro_core.egg-info/requires.txt
15
+ teleopro_core.egg-info/top_level.txt
16
+ teleopro_core.egg-info/zip-safe
17
+ test/test_mapping.py
18
+ test/test_teleop.py
@@ -0,0 +1,4 @@
1
+ numpy
2
+
3
+ [test]
4
+ pytest
@@ -0,0 +1 @@
1
+ teleopro_core
@@ -0,0 +1,109 @@
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from teleopro_core.mapping import TeleopMapper
5
+ from teleopro_core.transforms import (
6
+ make_transform, matrix_to_quat, matrix_to_rotvec, quat_to_matrix,
7
+ rotvec_to_matrix, rpy_to_matrix)
8
+
9
+
10
+ def pose(xyz=(0, 0, 0), rpy=(0, 0, 0)):
11
+ return make_transform(rpy_to_matrix(*rpy), xyz)
12
+
13
+
14
+ ROBOT_REF = pose((0.4, 0.1, 0.3), (np.pi, 0, 0.3))
15
+ INPUT_REF = pose((1.0, 2.0, 1.5), (0.2, -0.1, 1.0))
16
+
17
+
18
+ def test_quat_roundtrip():
19
+ for rpy in [(0, 0, 0), (np.pi, 0, 0), (0.3, -1.2, 2.9), (0, np.pi, 0)]:
20
+ R = rpy_to_matrix(*rpy)
21
+ assert np.allclose(quat_to_matrix(matrix_to_quat(R)), R)
22
+
23
+
24
+ def test_rotvec_roundtrip():
25
+ for v in [(0, 0, 0), (0.1, 0.2, -0.3), (0, 0, 3.0)]:
26
+ assert np.allclose(matrix_to_rotvec(rotvec_to_matrix(np.array(v))), v)
27
+
28
+
29
+ def test_engage_does_not_jump():
30
+ m = TeleopMapper()
31
+ m.engage(INPUT_REF, ROBOT_REF)
32
+ assert np.allclose(m.update(INPUT_REF, 0.01), ROBOT_REF)
33
+
34
+
35
+ def test_relative_translation_identity_alignment():
36
+ m = TeleopMapper()
37
+ m.engage(INPUT_REF, ROBOT_REF)
38
+ moved = INPUT_REF.copy()
39
+ moved[:3, 3] += [0.05, -0.02, 0.01]
40
+ out = m.update(moved, 0.01)
41
+ assert np.allclose(out[:3, 3], ROBOT_REF[:3, 3] + [0.05, -0.02, 0.01])
42
+ assert np.allclose(out[:3, :3], ROBOT_REF[:3, :3])
43
+
44
+
45
+ def test_relative_alignment_rotates_motion():
46
+ # Input +x maps to robot +y
47
+ m = TeleopMapper(align=rpy_to_matrix(0, 0, np.pi / 2))
48
+ m.engage(INPUT_REF, ROBOT_REF)
49
+ moved = INPUT_REF.copy()
50
+ moved[:3, 3] += [0.1, 0, 0]
51
+ out = m.update(moved, 0.0)
52
+ assert np.allclose(out[:3, 3] - ROBOT_REF[:3, 3], [0, 0.1, 0])
53
+
54
+
55
+ def test_relative_rotation_about_input_axis():
56
+ m = TeleopMapper(align=rpy_to_matrix(0, 0, np.pi / 2))
57
+ m.engage(INPUT_REF, ROBOT_REF)
58
+ # Rotation about input x maps to robot y
59
+ moved = make_transform(rpy_to_matrix(0.3, 0, 0) @ INPUT_REF[:3, :3], INPUT_REF[:3, 3])
60
+ out = m.update(moved, 0.0)
61
+ delta = matrix_to_rotvec(out[:3, :3] @ ROBOT_REF[:3, :3].T)
62
+ assert np.allclose(delta, [0, 0.3, 0])
63
+
64
+
65
+ def test_scales():
66
+ m = TeleopMapper(translation_scale=0.5, rotation_scale=2.0)
67
+ m.engage(INPUT_REF, ROBOT_REF)
68
+ moved = make_transform(rpy_to_matrix(0, 0, 0.1) @ INPUT_REF[:3, :3],
69
+ INPUT_REF[:3, 3] + [0.2, 0, 0])
70
+ out = m.update(moved, 0.0)
71
+ assert np.allclose(out[:3, 3] - ROBOT_REF[:3, 3], [0.1, 0, 0])
72
+ assert np.allclose(matrix_to_rotvec(out[:3, :3] @ ROBOT_REF[:3, :3].T), [0, 0, 0.2])
73
+
74
+
75
+ def test_dof_mask_planar():
76
+ m = TeleopMapper(dof_mask=[1, 1, 0, 0, 0, 1])
77
+ m.engage(INPUT_REF, ROBOT_REF)
78
+ moved = make_transform(rpy_to_matrix(0.2, 0, 0.1) @ INPUT_REF[:3, :3],
79
+ INPUT_REF[:3, 3] + [0.1, 0.1, 0.1])
80
+ out = m.update(moved, 0.0)
81
+ assert np.allclose(out[:3, 3] - ROBOT_REF[:3, 3], [0.1, 0.1, 0])
82
+ w = matrix_to_rotvec(out[:3, :3] @ ROBOT_REF[:3, :3].T)
83
+ assert abs(w[0]) < 1e-9 and abs(w[1]) < 1e-9 and abs(w[2]) > 0.05
84
+
85
+
86
+ def test_velocity_limit():
87
+ m = TeleopMapper(max_lin_vel=1.0, max_ang_vel=1.0)
88
+ m.engage(INPUT_REF, ROBOT_REF)
89
+ moved = make_transform(rpy_to_matrix(0, 0, 1.0) @ INPUT_REF[:3, :3],
90
+ INPUT_REF[:3, 3] + [1.0, 0, 0])
91
+ out = m.update(moved, 0.01)
92
+ assert np.isclose(np.linalg.norm(out[:3, 3] - ROBOT_REF[:3, 3]), 0.01)
93
+ assert np.isclose(np.linalg.norm(matrix_to_rotvec(out[:3, :3] @ ROBOT_REF[:3, :3].T)), 0.01)
94
+
95
+
96
+ def test_workspace_clamp():
97
+ m = TeleopMapper(workspace_min=[0, -0.2, 0.2], workspace_max=[0.5, 0.2, 0.6])
98
+ m.engage(INPUT_REF, ROBOT_REF)
99
+ moved = INPUT_REF.copy()
100
+ moved[:3, 3] += [1.0, -1.0, 1.0]
101
+ out = m.update(moved, 0.0)
102
+ assert np.allclose(out[:3, 3], [0.5, -0.2, 0.6])
103
+
104
+
105
+ def test_invalid_args():
106
+ with pytest.raises(ValueError):
107
+ TeleopMapper(dof_mask=[1, 1, 1])
108
+ with pytest.raises(RuntimeError):
109
+ TeleopMapper().update(INPUT_REF, 0.01)
@@ -0,0 +1,172 @@
1
+ import numpy as np
2
+
3
+ from teleopro_core import as_matrix, as_pos_quat, Teleop
4
+ from teleopro_core.transforms import make_transform, matrix_to_rotvec, rpy_to_matrix
5
+
6
+ ROBOT = make_transform(rpy_to_matrix(np.pi, 0, 0), [0.4, 0.0, 0.4])
7
+ DEVICE = make_transform(np.eye(3), [1.0, 2.0, 1.0])
8
+
9
+
10
+ def moved(dx):
11
+ T = DEVICE.copy()
12
+ T[0, 3] += dx
13
+ return T
14
+
15
+
16
+ def make(**kw):
17
+ kw.setdefault('max_lin_vel', 0.0)
18
+ kw.setdefault('max_ang_vel', 0.0)
19
+ return Teleop(**kw)
20
+
21
+
22
+ def test_pose_formats_roundtrip():
23
+ xyz, quat = as_pos_quat(ROBOT)
24
+ assert np.allclose(as_matrix((xyz, quat)), ROBOT)
25
+
26
+
27
+ def test_holds_robot_pose_until_engaged():
28
+ t = make()
29
+ assert t.update(0.0, DEVICE, None) is None
30
+ assert np.allclose(t.update(0.01, DEVICE, ROBOT), ROBOT)
31
+ # Target stays latched
32
+ other = ROBOT.copy()
33
+ other[2, 3] -= 0.05
34
+ assert np.allclose(t.update(0.02, moved(0.1), other), ROBOT)
35
+ assert not t.engaged
36
+
37
+
38
+ def test_engage_follows_device():
39
+ t = make()
40
+ t.engage()
41
+ assert np.allclose(t.update(0.0, DEVICE, ROBOT), ROBOT)
42
+ assert t.engaged
43
+ out = t.update(0.01, moved(0.05))
44
+ assert np.allclose(out[:3, 3], ROBOT[:3, 3] + [0.05, 0, 0])
45
+
46
+
47
+ def test_engage_waits_for_robot_pose():
48
+ t = make()
49
+ t.engage()
50
+ assert t.needs_robot_pose
51
+ assert t.update(0.0, DEVICE, None) is None
52
+ assert not t.engaged
53
+ t.update(0.01, DEVICE, ROBOT)
54
+ assert t.engaged and not t.needs_robot_pose
55
+
56
+
57
+ def test_disengage_holds_last_target():
58
+ t = make()
59
+ t.engage()
60
+ t.update(0.0, DEVICE, ROBOT)
61
+ last = t.update(0.01, moved(0.05))
62
+ t.disengage()
63
+ assert np.allclose(t.update(0.02, moved(0.3), ROBOT), last)
64
+
65
+
66
+ def test_reengage_starts_from_robot_pose():
67
+ t = make()
68
+ t.engage()
69
+ t.update(0.0, DEVICE, ROBOT)
70
+ t.update(0.01, moved(0.05))
71
+ t.disengage()
72
+ t.engage()
73
+ assert np.allclose(t.update(0.02, moved(0.2), ROBOT), ROBOT)
74
+
75
+
76
+ def test_input_lost_holds_then_reanchors():
77
+ t = make()
78
+ t.engage()
79
+ t.update(0.0, DEVICE, ROBOT)
80
+ last = t.update(0.01, moved(0.05))
81
+ assert np.allclose(t.update(0.02, None), last) # lost
82
+ assert np.allclose(t.update(0.03, moved(0.5)), last) # re-anchored
83
+ out = t.update(0.04, moved(0.52)) # following
84
+ assert np.allclose(out[:3, 3], last[:3, 3] + [0.02, 0, 0])
85
+
86
+
87
+ def test_stale_stamp_counts_as_lost():
88
+ t = make(input_timeout=0.2)
89
+ t.engage()
90
+ t.update(0.0, DEVICE, ROBOT, input_stamp=0.0)
91
+ last = t.update(0.1, moved(0.05), input_stamp=0.1)
92
+ # Stale stamp
93
+ assert np.allclose(t.update(0.5, moved(0.3), input_stamp=0.1), last)
94
+
95
+
96
+ def test_accepts_xyz_quat_input():
97
+ t = make()
98
+ t.engage()
99
+ t.update(0.0, as_pos_quat(DEVICE), as_pos_quat(ROBOT))
100
+ out = t.update(0.01, ((1.05, 2.0, 1.0), (0, 0, 0, 1)))
101
+ assert np.allclose(out[:3, 3], ROBOT[:3, 3] + [0.05, 0, 0])
102
+
103
+
104
+ # Twist input
105
+
106
+ ZERO = (0.0, 0.0, 0.0)
107
+
108
+
109
+ def test_twist_holds_until_engaged():
110
+ t = make()
111
+ assert np.allclose(t.update_twist(0.0, ((0.1, 0, 0), ZERO), ROBOT), ROBOT)
112
+ assert np.allclose(t.update_twist(1.0, ((0.1, 0, 0), ZERO), ROBOT), ROBOT)
113
+
114
+
115
+ def test_twist_base_frame():
116
+ t = make()
117
+ t.engage()
118
+ t.update_twist(0.0, (ZERO, ZERO), ROBOT)
119
+ out = t.update_twist(0.5, ((0.1, 0, 0.2), ZERO))
120
+ assert np.allclose(out[:3, 3], ROBOT[:3, 3] + [0.05, 0, 0.1])
121
+ assert np.allclose(out[:3, :3], ROBOT[:3, :3])
122
+
123
+
124
+ def test_twist_tool_frame():
125
+ # ROBOT tool is flipped about x: tool +z points along base -z
126
+ t = make(twist_frame='tool')
127
+ t.engage()
128
+ t.update_twist(0.0, (ZERO, ZERO), ROBOT)
129
+ out = t.update_twist(0.5, ((0, 0, 0.1), ZERO))
130
+ assert np.allclose(out[:3, 3], ROBOT[:3, 3] + [0, 0, -0.05])
131
+
132
+
133
+ def test_twist_rotation():
134
+ t = make()
135
+ t.engage()
136
+ t.update_twist(0.0, (ZERO, ZERO), ROBOT)
137
+ out = t.update_twist(1.0, (ZERO, (0, 0, 0.2)))
138
+ w = matrix_to_rotvec(out[:3, :3] @ ROBOT[:3, :3].T)
139
+ assert np.allclose(w, [0, 0, 0.2])
140
+
141
+
142
+ def test_twist_stale_stops():
143
+ t = make(input_timeout=0.2)
144
+ t.engage()
145
+ t.update_twist(0.0, (ZERO, ZERO), ROBOT, twist_stamp=0.0)
146
+ last = t.update_twist(0.1, ((0.1, 0, 0), ZERO), twist_stamp=0.1)
147
+ assert np.allclose(t.update_twist(1.0, ((0.1, 0, 0), ZERO), twist_stamp=0.1), last)
148
+ assert np.allclose(t.update_twist(1.1, None), last)
149
+
150
+
151
+ def test_twist_dof_mask_and_scale():
152
+ t = make(dof_mask=[1, 0, 1, 0, 0, 1], translation_scale=2.0)
153
+ t.engage()
154
+ t.update_twist(0.0, (ZERO, ZERO), ROBOT)
155
+ out = t.update_twist(0.5, ((0.1, 0.1, 0), (0.3, 0, 0)))
156
+ assert np.allclose(out[:3, 3], ROBOT[:3, 3] + [0.1, 0, 0])
157
+ assert np.allclose(out[:3, :3], ROBOT[:3, :3])
158
+
159
+
160
+ def test_twist_disengage_holds():
161
+ t = make()
162
+ t.engage()
163
+ t.update_twist(0.0, (ZERO, ZERO), ROBOT)
164
+ last = t.update_twist(0.5, ((0.1, 0, 0), ZERO))
165
+ t.disengage()
166
+ assert np.allclose(t.update_twist(1.0, ((0.1, 0, 0), ZERO), ROBOT), last)
167
+
168
+
169
+ def test_invalid_twist_frame():
170
+ import pytest
171
+ with pytest.raises(ValueError):
172
+ Teleop(twist_frame='world')