rotoki 0.2.0__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.
rotoki/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Robotics tool kit for communication, simulation, and visualization."""
2
+
3
+ from .loader import *
4
+ from .message import *
5
+ from .navigation import *
6
+ from .node import *
7
+ from .planning import *
8
+ from .process import *
9
+ from .recorder import *
10
+ from .ros import *
11
+ from .simulator import *
12
+ from .topology import *
13
+ from .viewer import *
@@ -0,0 +1,40 @@
1
+ """Examples to read and copy, also runnable as commands like `rotoki-showcase` once installed."""
2
+
3
+ import runpy
4
+
5
+
6
+ def _run(example: str) -> None:
7
+ """Run an example module as if it were launched directly."""
8
+ runpy.run_module(f"rotoki.examples.{example}", run_name="__main__")
9
+
10
+
11
+ def showcase() -> None:
12
+ _run("simulation.showcase")
13
+
14
+
15
+ def view() -> None:
16
+ _run("visualization.view")
17
+
18
+
19
+ def plan() -> None:
20
+ _run("simulation.plan")
21
+
22
+
23
+ def navigate() -> None:
24
+ _run("simulation.navigate")
25
+
26
+
27
+ def send() -> None:
28
+ _run("communication.send")
29
+
30
+
31
+ def receive() -> None:
32
+ _run("communication.receive")
33
+
34
+
35
+ def record() -> None:
36
+ _run("communication.record")
37
+
38
+
39
+ def bridge() -> None:
40
+ _run("communication.bridge")
@@ -0,0 +1,9 @@
1
+ # Communication
2
+
3
+ Nodes that send and receive messages over the network. Run `rotoki-communicate` to send, receive, record, and replay together.
4
+
5
+ - `main.py` runs the send, receive, and record examples at once, as separate processes
6
+ - `send.py` sends Position messages to two channels on a schedule
7
+ - `receive.py` prints the Position messages it receives on those channels
8
+ - `record.py` records messages on every channel, then replays them when you press Enter
9
+ - `bridge.py` bridges messages to and from ROS 2, which needs `ros2 run rmw_zenoh_cpp rmw_zenohd` running
@@ -0,0 +1,8 @@
1
+ """Bridge with ROS 2 running `ros2 run rmw_zenoh_cpp rmw_zenohd` until interrupted with Ctrl+C."""
2
+
3
+ from rotoki import JointState, Pose, RosNode
4
+
5
+ with RosNode("rotoki_example") as node:
6
+ node.receive_ros("/joint_states", JointState, print)
7
+ node.schedule(0.5, node.send_ros, "/pose", Pose.from_xyz(1, 2, 3))
8
+ node.spin()
@@ -0,0 +1,15 @@
1
+ """Sends data from one process to another, records it, and replays."""
2
+
3
+ from pathlib import Path
4
+
5
+ from rotoki import compose
6
+
7
+
8
+ def main() -> None:
9
+ here = Path(__file__).parent
10
+ programs = ["receive.py", "record.py", "send.py"]
11
+ compose([here / program for program in programs])
12
+
13
+
14
+ if __name__ == "__main__":
15
+ main()
@@ -0,0 +1,8 @@
1
+ """Receives Position messages from two channels until interrupted with Ctrl+C."""
2
+
3
+ from rotoki import Node, Position
4
+
5
+ with Node("receiver") as node:
6
+ node.receive("channel_0", lambda message: print(Position.decode(message)))
7
+ node.receive("channel_1", lambda message: print(Position.decode(message)))
8
+ node.spin()
@@ -0,0 +1,9 @@
1
+ """Records messages sent on any channel, then replays them. Run `rotoki-receive` to see the replay."""
2
+
3
+ from rotoki import Recorder
4
+
5
+ with Recorder("recorder") as recorder:
6
+ recorder.record()
7
+ input("Recording, press Enter to replay...")
8
+ recorder.stop()
9
+ recorder.play()
@@ -0,0 +1,8 @@
1
+ """Schedules sending Position messages to two channels until interrupted with Ctrl+C."""
2
+
3
+ from rotoki import Node, Position
4
+
5
+ with Node("sender") as node:
6
+ node.schedule(0.5, node.send, "channel_0", Position(x=1, y=2, z=3))
7
+ node.schedule(1.0, node.send, "channel_1", Position(x=4, y=5, z=6))
8
+ node.spin()
@@ -0,0 +1,9 @@
1
+ # Mobile manipulator
2
+
3
+ A TidyBot that carries a cube between two tables, then replays its recording on a loop. Run it with `rotoki-demo`.
4
+
5
+ - `main.py` runs the other programs here at once, as separate processes
6
+ - `sim.py` simulates the TidyBot, picking up the cube and carrying it to each goal it receives, with a wrist camera, planned paths, and a Teleop Mode to drive it yourself
7
+ - `commander.py` sends goals that carry the cube back and forth between the tables
8
+ - `recorder.py` records the TidyBot's joint states for two trips to `recording.msgpack` in the current directory, then replays them on a loop
9
+ - `bridge.py` bridges joint states and goal poses to ROS 2, which needs `ros2 run rmw_zenoh_cpp rmw_zenohd` running
File without changes
@@ -0,0 +1,17 @@
1
+ """Bridges the arm to ROS 2 running `ros2 run rmw_zenoh_cpp rmw_zenohd`."""
2
+
3
+ from rotoki import JointState, Node, Pose, RosNode
4
+
5
+
6
+ def send_joint_states(sample):
7
+ ros.send_ros("/joint_states", JointState.decode(sample))
8
+
9
+
10
+ def send_goal(goal):
11
+ node.send("goal", goal)
12
+
13
+
14
+ with Node("bridge") as node, RosNode("rotoki_bridge") as ros:
15
+ node.receive("joint_states", send_joint_states)
16
+ ros.receive_ros("/goal_pose", Pose, send_goal)
17
+ node.spin()
@@ -0,0 +1,21 @@
1
+ """Sends the arm a goal to carry the cube back and forth between the two tables."""
2
+
3
+ import threading
4
+ import time
5
+ from contextlib import suppress
6
+ from itertools import cycle
7
+
8
+ from rotoki import Node, Pose
9
+
10
+ # Where the cube's center goes, resting on top of each table
11
+ goals = cycle([(-0.5, 1.2, 0.625), (1.0, 0.0, 0.625)])
12
+ placed = threading.Event()
13
+
14
+ time.sleep(5) # Give the arm time to load before the first goal
15
+
16
+ with Node("commander") as node, suppress(KeyboardInterrupt):
17
+ node.receive("placed", lambda sample: placed.set())
18
+ for goal in goals:
19
+ placed.clear()
20
+ node.send("goal", Pose.from_xyz(*goal))
21
+ placed.wait(40) # Move on anyway if the arm gave up on the goal
@@ -0,0 +1,15 @@
1
+ """Carries the cube there and back, then replays the recording on a loop. Stop with Ctrl+C."""
2
+
3
+ from pathlib import Path
4
+
5
+ from rotoki import compose
6
+
7
+
8
+ def main() -> None:
9
+ here = Path(__file__).parent
10
+ programs = ["sim.py", "bridge.py", "commander.py", "recorder.py"]
11
+ compose([here / program for program in programs])
12
+
13
+
14
+ if __name__ == "__main__":
15
+ main()
@@ -0,0 +1,23 @@
1
+ """Records the arm's joint states while it carries the cube there and back to recording.msgpack in the current directory, then replays them on a loop."""
2
+
3
+ import threading
4
+ import time
5
+ from contextlib import suppress
6
+
7
+ from rotoki import Recorder
8
+
9
+ placements = threading.Semaphore(0)
10
+
11
+ with Recorder("recorder", "joint_states") as recorder:
12
+ recorder.receive("placed", lambda sample: placements.release())
13
+ time.sleep(5) # Give the arm time to load before recording
14
+ recorder.record()
15
+ # Stop once the cube is back where it started, so the replay loops without a pause
16
+ for _ in range(2):
17
+ placements.acquire(timeout=60)
18
+ recorder.stop()
19
+ recorder.save("recording.msgpack")
20
+ print(f"recorder: saved {len(recorder.records)} messages, now replaying")
21
+ recorder.send("replay", b"")
22
+ with suppress(KeyboardInterrupt):
23
+ recorder.play(loop=True)
@@ -0,0 +1,329 @@
1
+ """Simulates a TidyBot that picks up a cube and carries it to each goal it receives."""
2
+
3
+ import copy
4
+ import html
5
+ from dataclasses import dataclass, field
6
+
7
+ import numpy as np
8
+
9
+ from rotoki import *
10
+
11
+ CUBE_SIZE = 0.025 # Half the cube's width
12
+ ABOVE = np.array([0.0, 0.0, 0.12]) # Where the gripper waits above a pick or place
13
+ GRIP = np.array([0.0, 0.0, 0.015])
14
+ RELEASE = GRIP + [0.0, 0.0, 0.005]
15
+ # Teleop's drive buttons and their keys, each with the forward and turning direction it adds
16
+ DRIVE_BUTTONS = {
17
+ "Forward (W)": (1.0, 0.0),
18
+ "Back (S)": (-1.0, 0.0),
19
+ "Left (A)": (0.0, 1.0),
20
+ "Right (D)": (0.0, -1.0),
21
+ }
22
+ TOP_SPEEDS = np.array([0.4, 0.8]) # Driving forward in m/s and turning in rad/s
23
+ ACCELERATIONS = np.array([1.0, 2.0]) # How fast the base gets up to and down from them
24
+ ARM_SPEED = 1.0 # rad/s that the arm follows its sliders at
25
+ # Holds the teleop drive button for a key while it's pressed, and keeps the key from the camera
26
+ KEYBOARD_SCRIPT = """
27
+ if (!window.teleopKeys) {
28
+ window.teleopKeys = true;
29
+ const buttons = {KeyW: 'Forward (W)', KeyS: 'Back (S)', KeyA: 'Left (A)', KeyD: 'Right (D)'};
30
+ const find = (label) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim() === label);
31
+ const press = (event, type) => {
32
+ const button = buttons[event.code] && find(buttons[event.code]);
33
+ if (!button || event.target.closest('input, textarea')) return;
34
+ event.stopImmediatePropagation();
35
+ event.preventDefault();
36
+ if (!event.repeat) button.dispatchEvent(new PointerEvent(type, {bubbles: true}));
37
+ };
38
+ window.addEventListener('keydown', (event) => press(event, 'pointerdown'), true);
39
+ window.addEventListener('keyup', (event) => press(event, 'pointerup'), true);
40
+ }
41
+ """
42
+
43
+ sim = open_sim()
44
+ add_sim_robot(sim, "stanford_tidybot", "arm")
45
+ add_sim_box(sim, "box_0", (1.0, 0.0, 0.3), (0.2, 0.3, 0.3))
46
+ add_sim_box(sim, "box_1", (-0.5, 1.2, 0.3), (0.3, 0.2, 0.3))
47
+ add_sim_box(
48
+ sim,
49
+ "cube",
50
+ (1.0, 0.0, 0.6 + CUBE_SIZE),
51
+ (CUBE_SIZE,) * 3,
52
+ (0.9, 0.3, 0.2, 1.0),
53
+ mass=0.1,
54
+ )
55
+ model, data = build_sim(sim)
56
+ model.stat.extent = (
57
+ 1.0 # Start the view 3 m from the scene's center, closer than the default
58
+ )
59
+ # Plan as if the cube weren't there, so reaching around and carrying it aren't collisions
60
+ planning_model = copy.copy(model)
61
+ planning_model.geom_contype[model.geom("cube").id] = 0
62
+ planning_model.geom_conaffinity[model.geom("cube").id] = 0
63
+ base = get_wheeled_base(model, data, "arm")
64
+ actuator_ids, qpos_ids = get_joint_actuators(model, "arm")
65
+ fingers = model.actuator("arm/fingers_actuator").id
66
+ routes = []
67
+ trajectories = []
68
+ steps = [] # The pick-and-place steps left, each started once the one before ends
69
+ step_end = [0.0] # The sim time the current step ends
70
+ replayed = [] # The latest replayed joint positions, once replaying
71
+
72
+ server = open_viewer(port=8080)
73
+ replaying = False # Set once told to replay the recording
74
+ paths = add_paths(server) # The latest planned route and arm path
75
+ add_sim_camera(server, model, data, "arm/wrist")
76
+
77
+ # Teleop: drive the base with buttons or WASD, and move the arm with sliders
78
+ arm_actuators = [a for a in actuator_ids if a not in base.actuator_ids]
79
+
80
+
81
+ @dataclass
82
+ class Teleop:
83
+ on: bool = False
84
+ # Where the base is being driven to: x, y, and yaw
85
+ pose: np.ndarray = field(default_factory=lambda: np.zeros(3))
86
+ # How fast it's going forward and turning
87
+ velocity: np.ndarray = field(default_factory=lambda: np.zeros(2))
88
+ # Each drive button being held, until what sim time, as holds repeat while held
89
+ held: dict[str, float] = field(default_factory=dict)
90
+
91
+
92
+ teleop = Teleop()
93
+ # For checking the base won't drive into anything
94
+ scratch = mujoco.MjData(planning_model)
95
+ with server.gui.add_folder("Teleop"):
96
+ teleop_button = server.gui.add_button("Teleop Mode")
97
+ drive_buttons = {
98
+ label: server.gui.add_button(label, visible=False) for label in DRIVE_BUTTONS
99
+ }
100
+ arm_sliders = []
101
+ for actuator in arm_actuators:
102
+ joint = model.actuator_trnid[actuator, 0]
103
+ low, high = (
104
+ model.jnt_range[joint] if model.jnt_limited[joint] else (-np.pi, np.pi)
105
+ )
106
+ name = model.joint(joint).name.split("/")[-1].replace("_", " ").capitalize()
107
+ arm_sliders.append(
108
+ server.gui.add_slider(name, low, high, 0.01, 0.0, visible=False)
109
+ )
110
+ gripper_slider = server.gui.add_slider(
111
+ "Gripper", 0.0, 255.0, 1.0, 0.0, visible=False
112
+ )
113
+ # An image that fails to load runs the keyboard script, as HTML added here can't hold a script tag
114
+ server.gui.add_html(
115
+ f'<img src="data:," style="display: none" onerror="{html.escape(KEYBOARD_SCRIPT)}">'
116
+ )
117
+
118
+
119
+ @teleop_button.on_click
120
+ def toggle_teleop(_):
121
+ on = not teleop.on
122
+ if on:
123
+ # Stop carrying the cube, and start the controls from where the robot is
124
+ steps.clear()
125
+ routes.clear()
126
+ trajectories.clear()
127
+ paths.clear()
128
+ teleop.pose = get_base_pose(base, data)
129
+ teleop.velocity[:] = 0.0
130
+ for slider, actuator in zip(arm_sliders, arm_actuators):
131
+ joint = model.actuator_trnid[actuator, 0]
132
+ slider.value = float(
133
+ np.clip(data.qpos[model.jnt_qposadr[joint]], slider.min, slider.max)
134
+ )
135
+ gripper_slider.value = float(data.ctrl[fingers])
136
+ teleop.on = on
137
+ teleop_button.label = "Exit Teleop Mode" if on else "Teleop Mode"
138
+ for control in [*drive_buttons.values(), *arm_sliders, gripper_slider]:
139
+ control.visible = on
140
+ print(f"arm: teleop {'on' if on else 'off'}")
141
+
142
+
143
+ for label, button in drive_buttons.items():
144
+
145
+ @button.on_hold(callback_hz=20.0)
146
+ def hold(_, label=label):
147
+ # Held a little longer than the time between holds, in sim time like the driving
148
+ teleop.held[label] = data.time + 0.15
149
+
150
+
151
+ def on_goal(sample):
152
+ if replaying:
153
+ return
154
+ if teleop.on:
155
+ print("arm: in teleop mode, ignoring the goal")
156
+ return
157
+ if steps:
158
+ print("arm: still carrying the cube, ignoring the goal")
159
+ return
160
+ pick = data.body("cube").xpos.copy()
161
+ place = Pose.decode(sample).position
162
+ place = np.array([place.x, place.y, place.z])
163
+ print(f"arm: carrying the cube from {pick.round(2)} to {place.round(2)}")
164
+ steps[:] = [
165
+ lambda data: drive_to(data, pick),
166
+ lambda data: move_gripper(data, pick + ABOVE),
167
+ lambda data: move_gripper(data, pick + GRIP),
168
+ lambda data: grip(data, closed=True),
169
+ lambda data: move_gripper(data, pick + ABOVE),
170
+ lambda data: drive_to(data, place),
171
+ lambda data: move_gripper(data, place + ABOVE),
172
+ lambda data: move_gripper(data, place + RELEASE),
173
+ lambda data: grip(data, closed=False),
174
+ lambda data: move_gripper(data, place + ABOVE),
175
+ placed,
176
+ ]
177
+ step_end[0] = 0.0
178
+
179
+
180
+ def drive_to(data, target):
181
+ """Drive to stand short of the target, facing it, so the arm can reach it."""
182
+ x, y, _ = get_base_pose(base, data)
183
+ straight = np.arctan2(target[1] - y, target[0] - x)
184
+ for turn in np.radians([0, 30, -30, 60, -60, 90, -90]):
185
+ heading = straight + turn
186
+ stand = target[:2] - 0.6 * np.array([np.cos(heading), np.sin(heading)])
187
+ goal = Pose(Position(*stand, 0.0), Orientation.from_rpy(0, 0, heading))
188
+ try:
189
+ routes[:] = [plan_route(planning_model, data, base, goal)]
190
+ break
191
+ except PlanningError as error:
192
+ failure = error
193
+ else:
194
+ raise failure
195
+ paths.draw("route", get_route_path(routes[0]), (0, 150, 255))
196
+ paths.remove("arm_path")
197
+ return routes[0].times[-1]
198
+
199
+
200
+ def move_gripper(data, position):
201
+ """Move the gripper to a position, pointing down and across the base's heading."""
202
+ heading = get_base_pose(base, data)[2]
203
+ goal = Pose(
204
+ Position(*position), Orientation.from_rpy(np.pi, 0, heading + np.pi / 2)
205
+ )
206
+ trajectories[:] = [
207
+ plan_trajectory(
208
+ planning_model,
209
+ data,
210
+ "arm/pinch_site",
211
+ goal,
212
+ 0.5,
213
+ robot="arm",
214
+ fixed_joints=base.joint_ids,
215
+ )
216
+ ]
217
+ paths.draw(
218
+ "arm_path",
219
+ get_frame_path(model, data, "arm/pinch_site", trajectories[0]),
220
+ (255, 140, 0),
221
+ )
222
+ return trajectories[0].times[-1]
223
+
224
+
225
+ def grip(data, closed):
226
+ data.ctrl[fingers] = 255 if closed else 0
227
+ return data.time + 1.0 # Time for the fingers to close or open
228
+
229
+
230
+ def placed(data):
231
+ """Tell the commander and recorder the cube is at its goal and the gripper is clear."""
232
+ node.send("placed", b"")
233
+ return data.time
234
+
235
+
236
+ def on_replay(sample):
237
+ global replaying
238
+ replaying = True
239
+ set_banner(server, "Replay", dark_mode=True)
240
+ paths.clear() # The replay isn't following a plan
241
+ print("arm: now replaying")
242
+
243
+
244
+ def on_joint_states(sample):
245
+ if replaying:
246
+ replayed[:] = [np.array(JointState.decode(sample).positions)]
247
+
248
+
249
+ def send_joint_states(node):
250
+ if not replaying:
251
+ node.send("joint_states", JointState(get_joint_positions(data).tolist()))
252
+
253
+
254
+ def advance(pose, velocity, seconds):
255
+ """Where the base gets to from a pose of x, y, and yaw, going at a forward and turning velocity."""
256
+ (x, y, yaw), (forward, turn) = pose, velocity
257
+ distance = forward * seconds
258
+ return np.array(
259
+ [x + distance * np.cos(yaw), y + distance * np.sin(yaw), yaw + turn * seconds]
260
+ )
261
+
262
+
263
+ def is_clear(data, pose):
264
+ scratch.qpos[:] = data.qpos
265
+ return is_base_collision_free(planning_model, scratch, base, pose)
266
+
267
+
268
+ def drive_teleop(data):
269
+ """Drive the base from the held buttons, and move the arm toward its sliders."""
270
+ dt = model.opt.timestep
271
+ held = [
272
+ DRIVE_BUTTONS[label]
273
+ for label, until in teleop.held.items()
274
+ if until > data.time
275
+ ]
276
+ wanted = np.sum(held, axis=0) * TOP_SPEEDS if held else np.zeros(2)
277
+ if teleop.velocity.any():
278
+ # Brake in time if carrying on would reach something within the distance it takes to stop
279
+ stopping_time = (np.abs(teleop.velocity) / ACCELERATIONS).max()
280
+ if not is_clear(
281
+ data, advance(teleop.pose, teleop.velocity, stopping_time / 2 + 0.05)
282
+ ):
283
+ wanted = np.zeros(2)
284
+ limit = ACCELERATIONS * dt
285
+ teleop.velocity += np.clip(wanted - teleop.velocity, -limit, limit)
286
+ if teleop.velocity.any():
287
+ pose = advance(teleop.pose, teleop.velocity, dt)
288
+ if is_clear(data, pose):
289
+ teleop.pose = pose
290
+ else:
291
+ teleop.velocity[:] = (
292
+ 0.0 # Braking wasn't enough, so stop dead rather than drive in
293
+ )
294
+ # A route that stays at one pose holds the base there
295
+ drive_route(base, data, Trajectory([JointState(teleop.pose.tolist())], [0.0]))
296
+ targets = np.array([slider.value for slider in arm_sliders])
297
+ step = np.clip(targets - data.ctrl[arm_actuators], -ARM_SPEED * dt, ARM_SPEED * dt)
298
+ data.ctrl[arm_actuators] += step
299
+ data.ctrl[fingers] = gripper_slider.value
300
+
301
+
302
+ def control(data):
303
+ if teleop.on:
304
+ drive_teleop(data)
305
+ elif not replaying:
306
+ if steps and data.time >= step_end[0]:
307
+ step = steps.pop(0)
308
+ try:
309
+ step_end[0] = step(data)
310
+ except PlanningError as error:
311
+ print(f"arm: giving up on the cube: {error}")
312
+ steps.clear()
313
+ if routes:
314
+ drive_route(base, data, routes[0])
315
+ for trajectory in trajectories:
316
+ apply_controls(model, data, trajectory)
317
+ elif replayed:
318
+ data.qpos[:] = replayed[0]
319
+ data.qvel[:] = 0.0
320
+ data.ctrl[actuator_ids] = replayed[0][qpos_ids]
321
+
322
+
323
+ with Node("arm") as node:
324
+ node.receive("goal", on_goal)
325
+ node.receive("replay", on_replay)
326
+ node.receive("joint_states", on_joint_states)
327
+ node.schedule(0.05, send_joint_states, node)
328
+ add_node_graph(server, node)
329
+ run_sim(model, data, control, server)
@@ -0,0 +1,7 @@
1
+ # Simulation
2
+
3
+ Robots simulated in MuJoCo and shown in a web viewer at http://localhost:8080.
4
+
5
+ - `showcase.py` simulates a lineup of robots: quadrupeds and a humanoid standing, arms swaying, and a drone hovering
6
+ - `plan.py` plans collision-free trajectories for two Franka Pandas and follows them
7
+ - `navigate.py` plans a route for a Stretch 3 to drive around a box to a goal
@@ -0,0 +1,15 @@
1
+ """Simulate a Stretch 3 driving around a box to a goal. Hit Ctrl+C to stop."""
2
+
3
+ from rotoki import *
4
+
5
+ sim = open_sim()
6
+ add_sim_robot(sim, "hello_robot_stretch_3", "stretch")
7
+ add_sim_box(sim, "box", (0.7, 0.0, 0.3), (0.1, 0.2, 0.3))
8
+ model, data = build_sim(sim)
9
+ base = get_wheeled_base(model, data, "stretch")
10
+ goal = Pose(Position(1.4, 0.0, 0.0), Orientation.from_rpy(0, 0, 0))
11
+ route = plan_route(model, data, base, goal)
12
+ server = open_viewer()
13
+ paths = add_paths(server)
14
+ paths.draw("route", get_route_path(route), (0, 150, 255))
15
+ run_sim(model, data, lambda data: drive_route(base, data, route), server)
@@ -0,0 +1,17 @@
1
+ """Simulate two Franka Pandas following trajectories. Hit Load to home and Ctrl+C to stop."""
2
+
3
+ from rotoki import *
4
+
5
+ sim = open_sim()
6
+ add_sim_robot(sim, "franka_emika_panda", "panda0")
7
+ add_sim_robot(sim, "franka_emika_panda", "panda1", (1.5, 0, 0), (0, 0, 3.14))
8
+ model, data = build_sim(sim)
9
+ goal_0 = Pose.from_xyz(0.5, 0.3, 0.5)
10
+ goal_1 = Pose.from_xyz(1.0, -0.3, 0.5)
11
+ traj_0 = plan_trajectory(model, data, "panda0/hand", goal_0, 0.5, robot="panda0")
12
+ traj_1 = plan_trajectory(model, data, "panda1/hand", goal_1, 0.5, robot="panda1")
13
+ server = open_viewer()
14
+ paths = add_paths(server)
15
+ paths.draw("panda0", get_frame_path(model, data, "panda0/hand", traj_0))
16
+ paths.draw("panda1", get_frame_path(model, data, "panda1/hand", traj_1))
17
+ run_sim(model, data, [traj_0, traj_1], server)
@@ -0,0 +1,59 @@
1
+ """Simulate a lineup of robots. Hit Ctrl+C to stop."""
2
+
3
+ import mujoco
4
+ import numpy as np
5
+
6
+ from rotoki import *
7
+
8
+ STANDING = [
9
+ ("boston_dynamics_spot", (1.4, 1.0)),
10
+ ("unitree_g1", (0.0, 1.0)),
11
+ ("anybotics_anymal_c", (-1.4, 1.0)),
12
+ ]
13
+ ARMS = [
14
+ ("franka_fr3", (1.8, -0.6)),
15
+ ("kinova_gen3", (0.6, -0.6)),
16
+ ("universal_robots_ur10e", (-0.6, -0.6)),
17
+ ("unitree_z1", (-1.8, -0.6)),
18
+ ]
19
+ DRONE = "skydio_x2"
20
+ DRONE_HEIGHT = 2.0
21
+ ANYMAL_STANCE = {"HFE": (0.4, -0.4), "KFE": (-0.8, 0.8)}
22
+
23
+ sim = open_sim()
24
+ for name, (x, y) in STANDING + ARMS:
25
+ add_sim_robot(sim, name, name, (x, y, 0.0), (0, 0, -np.pi / 2))
26
+ add_sim_robot(sim, DRONE, DRONE, (0.0, 0.2, DRONE_HEIGHT))
27
+ model, data = build_sim(sim)
28
+
29
+ for leg in ("LF", "RF", "LH", "RH"):
30
+ for joint, (front, hind) in ANYMAL_STANCE.items():
31
+ name = f"anybotics_anymal_c/{leg}_{joint}"
32
+ data.joint(name).qpos = front if leg.endswith("F") else hind
33
+ mujoco.mj_forward(model, data)
34
+
35
+ home = data.ctrl.copy()
36
+ for name, _ in STANDING:
37
+ actuators, qpos_ids = get_joint_actuators(model, name)
38
+ home[actuators] = data.qpos[qpos_ids]
39
+ swaying = [get_joint_actuators(model, name)[0] for name, _ in ARMS]
40
+ drone_body = model.body(f"{DRONE}/x2").id
41
+ propellers = [a for a in range(model.nu) if model.actuator(a).name.startswith(DRONE)]
42
+ low, high = model.actuator_ctrlrange.T
43
+ limited = model.actuator_ctrllimited.astype(bool)
44
+
45
+
46
+ def animate(data):
47
+ t = data.time
48
+ data.ctrl[:] = home
49
+ for arm, actuators in enumerate(swaying):
50
+ phase = arm + np.arange(len(actuators))
51
+ data.ctrl[actuators] += 0.3 * np.sin(0.8 * t + phase)
52
+ height = DRONE_HEIGHT + 0.2 * np.sin(0.5 * t)
53
+ climb = data.cvel[drone_body][5]
54
+ error = height - data.xpos[drone_body][2]
55
+ data.ctrl[propellers] += 4.0 * error - 2.0 * climb
56
+ data.ctrl[limited] = np.clip(data.ctrl[limited], low[limited], high[limited])
57
+
58
+
59
+ run_sim(model, data, animate)
@@ -0,0 +1,5 @@
1
+ # Visualization
2
+
3
+ Robots shown in a web viewer at http://localhost:8080, without simulating them.
4
+
5
+ - `view.py` shows two Unitree Go2s with joint sliders, live camera panels, and a graph of the nodes on the network
@@ -0,0 +1,15 @@
1
+ """View two Unitree Go2s with joint sliders, cameras, and a graph of the network until interrupted with Ctrl+C."""
2
+
3
+ from rotoki import Node, add_node_graph, add_robot, load_urdf, open_viewer, run_viewer
4
+
5
+ server = open_viewer(dark_mode=True)
6
+ standing = [0.0, 0.8, -1.5] * 4 # hip, thigh, calf for each leg
7
+ cameras = ["front_camera"]
8
+ orientation = (0.0, 0.0, 3.14)
9
+ go2_a = load_urdf("go2_description")
10
+ go2_b = load_urdf("go2_description")
11
+ add_robot(server, go2_a, standing, "go2_a", cameras=cameras)
12
+ add_robot(server, go2_b, standing, "go2_b", (1.5, 0, 0), orientation, cameras=cameras)
13
+ with Node("viewer") as node:
14
+ add_node_graph(server, node)
15
+ run_viewer(server)