livingproof-sim-mujoco 3.10.2__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.
- livingproof_sim_mujoco/__init__.py +5 -0
- livingproof_sim_mujoco/_build_provenance.json +14 -0
- livingproof_sim_mujoco/adapters.py +133 -0
- livingproof_sim_mujoco/binding.py +122 -0
- livingproof_sim_mujoco/cli.py +272 -0
- livingproof_sim_mujoco/compat/__init__.py +2 -0
- livingproof_sim_mujoco/compat/hallway.py +94 -0
- livingproof_sim_mujoco/compat/parameters.json +68 -0
- livingproof_sim_mujoco/compose.py +343 -0
- livingproof_sim_mujoco/contract/hallway-probe.json +58 -0
- livingproof_sim_mujoco/contract/hallway-quantities.json +87 -0
- livingproof_sim_mujoco/contract/hallway-result.schema.json +91 -0
- livingproof_sim_mujoco/contract/pins.json +11 -0
- livingproof_sim_mujoco/contract.py +174 -0
- livingproof_sim_mujoco/cpu.py +62 -0
- livingproof_sim_mujoco/evidence.py +1502 -0
- livingproof_sim_mujoco/hallway.py +925 -0
- livingproof_sim_mujoco/measure.py +43 -0
- livingproof_sim_mujoco/media.py +522 -0
- livingproof_sim_mujoco/models/falling.xml +10 -0
- livingproof_sim_mujoco/observations.py +658 -0
- livingproof_sim_mujoco/pins.py +366 -0
- livingproof_sim_mujoco/policy.py +456 -0
- livingproof_sim_mujoco/robot_topics.py +125 -0
- livingproof_sim_mujoco/scenario.py +398 -0
- livingproof_sim_mujoco/scenarios/catalog.json +11 -0
- livingproof_sim_mujoco/scenarios/walk-corner/0.1.0/parameters.json +63 -0
- livingproof_sim_mujoco/scene.py +90 -0
- livingproof_sim_mujoco/sources.py +188 -0
- livingproof_sim_mujoco/walk.py +249 -0
- livingproof_sim_mujoco/world_shapes.py +172 -0
- livingproof_sim_mujoco/worlds/hallway-corner/0.1.0/notes.md +38 -0
- livingproof_sim_mujoco/worlds/hallway-corner/0.1.0/release.json +12 -0
- livingproof_sim_mujoco/worlds/hallway-corner/0.1.0/world.json +54 -0
- livingproof_sim_mujoco/worlds/hallway-corner-0.1.0.mujoco.json +16 -0
- livingproof_sim_mujoco/worlds/hallway-open/0.1.0/notes.md +31 -0
- livingproof_sim_mujoco/worlds/hallway-open/0.1.0/release.json +12 -0
- livingproof_sim_mujoco/worlds/hallway-open/0.1.0/world.json +55 -0
- livingproof_sim_mujoco/worlds/hallway-open-0.1.0.mujoco.json +16 -0
- livingproof_sim_mujoco/worlds/pins.json +18 -0
- livingproof_sim_mujoco/worlds/same-bytes.json +15 -0
- livingproof_sim_mujoco/worlds/schema/pins.json +10 -0
- livingproof_sim_mujoco/worlds/schema/world-0.3.schema.json +475 -0
- livingproof_sim_mujoco/worlds/schema/world.schema.json +111 -0
- livingproof_sim_mujoco-3.10.2.dist-info/METADATA +164 -0
- livingproof_sim_mujoco-3.10.2.dist-info/RECORD +49 -0
- livingproof_sim_mujoco-3.10.2.dist-info/WHEEL +4 -0
- livingproof_sim_mujoco-3.10.2.dist-info/entry_points.txt +2 -0
- livingproof_sim_mujoco-3.10.2.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"distribution": "livingproof-sim-mujoco",
|
|
3
|
+
"format_version": 1,
|
|
4
|
+
"identity": {
|
|
5
|
+
"base_version": "3.10.2",
|
|
6
|
+
"branch": "detached",
|
|
7
|
+
"commit": "d22c479d0fb5355105660ff079fec262777094a2",
|
|
8
|
+
"distance": 0,
|
|
9
|
+
"format_version": 1,
|
|
10
|
+
"history": "tagged",
|
|
11
|
+
"state": "clean"
|
|
12
|
+
},
|
|
13
|
+
"package_version": "3.10.2"
|
|
14
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Build a ``PolicySpec`` from a published controller's own deploy configuration.
|
|
3
|
+
|
|
4
|
+
Each adapter takes the upstream values unchanged, so the numbers stay in the upstream
|
|
5
|
+
file rather than being copied into code. The robot package supplies only the mapping
|
|
6
|
+
from upstream joint indices to model joint and actuator names.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping, Sequence
|
|
12
|
+
import math
|
|
13
|
+
|
|
14
|
+
from livingproof_sim_mujoco.policy import ObsTerm, PolicySpec
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def rl_gym(
|
|
18
|
+
deploy: Mapping,
|
|
19
|
+
*,
|
|
20
|
+
physics_dt: float,
|
|
21
|
+
joints: Sequence[str],
|
|
22
|
+
actuators: Sequence[str],
|
|
23
|
+
hold_joints: Sequence[str] = (),
|
|
24
|
+
hold_actuators: Sequence[str] = (),
|
|
25
|
+
gait_period: float = 0.8,
|
|
26
|
+
) -> PolicySpec:
|
|
27
|
+
"""unitree_rl_gym ``deploy_real/configs/<robot>.yaml`` plus ``deploy_mujoco.py``.
|
|
28
|
+
|
|
29
|
+
Observation (``num_obs``): base angular velocity * ang_vel_scale, projected gravity
|
|
30
|
+
from the pelvis quaternion, command * cmd_scale, (q - default) * dof_pos_scale,
|
|
31
|
+
dq * dof_vel_scale, last action, then [sin, cos] of a ``gait_period`` phase
|
|
32
|
+
(0.8 s in deploy_mujoco.py and deploy_real.py). Targets default + action *
|
|
33
|
+
action_scale, tracked by a torque PD with ``kps``/``kds``; arm and waist joints are
|
|
34
|
+
held at ``arm_waist_target`` with ``arm_waist_kps``/``arm_waist_kds``.
|
|
35
|
+
"""
|
|
36
|
+
n = int(deploy["num_actions"])
|
|
37
|
+
if len(joints) != n or len(actuators) != n:
|
|
38
|
+
raise ValueError(f"num_actions is {n}; got {len(joints)} joints")
|
|
39
|
+
decimation = round(float(deploy["control_dt"]) / physics_dt)
|
|
40
|
+
if not math.isclose(decimation * physics_dt, float(deploy["control_dt"])):
|
|
41
|
+
raise ValueError("control_dt is not a whole number of physics steps")
|
|
42
|
+
hold = []
|
|
43
|
+
if hold_joints:
|
|
44
|
+
targets, kps, kds = (
|
|
45
|
+
deploy[k] for k in ("arm_waist_target", "arm_waist_kps", "arm_waist_kds")
|
|
46
|
+
)
|
|
47
|
+
if not (len(hold_joints) == len(hold_actuators) == len(targets)):
|
|
48
|
+
raise ValueError("hold joints must match arm_waist_target")
|
|
49
|
+
hold = [
|
|
50
|
+
(j, a, float(t), float(p), float(d))
|
|
51
|
+
for j, a, t, p, d in zip(hold_joints, hold_actuators, targets, kps, kds)
|
|
52
|
+
]
|
|
53
|
+
# deploy_mujoco.py evaluates the policy after `counter` physics steps, so the first
|
|
54
|
+
# phase is one control period in: phase = (k * control_dt % period) / period, k >= 1.
|
|
55
|
+
rate = 1.0 / gait_period
|
|
56
|
+
first = 2 * math.pi * rate * float(deploy["control_dt"])
|
|
57
|
+
spec = PolicySpec(
|
|
58
|
+
joints=list(joints),
|
|
59
|
+
actuators=list(actuators),
|
|
60
|
+
default_pose=[float(v) for v in deploy["default_angles"]],
|
|
61
|
+
action_scale=float(deploy["action_scale"]),
|
|
62
|
+
decimation=decimation,
|
|
63
|
+
obs=[
|
|
64
|
+
ObsTerm("base_angvel", scale=float(deploy["ang_vel_scale"])),
|
|
65
|
+
ObsTerm("gravity", "body:" + deploy.get("imu_body", "pelvis")),
|
|
66
|
+
ObsTerm("command", scale=[float(v) for v in deploy["cmd_scale"]]),
|
|
67
|
+
ObsTerm("joint_pos", scale=float(deploy["dof_pos_scale"])),
|
|
68
|
+
ObsTerm("joint_vel", scale=float(deploy["dof_vel_scale"])),
|
|
69
|
+
ObsTerm("last_action"),
|
|
70
|
+
ObsTerm("phase"),
|
|
71
|
+
],
|
|
72
|
+
gait_hz=rate,
|
|
73
|
+
gait_offsets=[math.remainder(first, 2 * math.pi)],
|
|
74
|
+
phase_order="sin_cos",
|
|
75
|
+
actuation="pd_torque",
|
|
76
|
+
kp=[float(v) for v in deploy["kps"]],
|
|
77
|
+
kd=[float(v) for v in deploy["kds"]],
|
|
78
|
+
hold=hold,
|
|
79
|
+
)
|
|
80
|
+
if 9 + 3 * n + 2 != int(deploy["num_obs"]):
|
|
81
|
+
raise ValueError("num_obs does not match the rl_gym observation layout")
|
|
82
|
+
return spec
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def playground_joystick(
|
|
86
|
+
*,
|
|
87
|
+
physics_dt: float,
|
|
88
|
+
ctrl_dt: float,
|
|
89
|
+
joints: Sequence[str],
|
|
90
|
+
actuators: Sequence[str],
|
|
91
|
+
default_pose: Sequence[float],
|
|
92
|
+
action_scale: float,
|
|
93
|
+
gait_hz: float,
|
|
94
|
+
gait_offsets: Sequence[float],
|
|
95
|
+
linvel_sensor: str,
|
|
96
|
+
gyro_sensor: str,
|
|
97
|
+
imu_site: str,
|
|
98
|
+
actuation: str = "position",
|
|
99
|
+
kp: Sequence[float] = (),
|
|
100
|
+
kd: Sequence[float] = (),
|
|
101
|
+
) -> PolicySpec:
|
|
102
|
+
"""MuJoCo Playground joystick policies (``experimental/sim2sim``).
|
|
103
|
+
|
|
104
|
+
Observation: local linear velocity, gyro, gravity in the IMU site frame, command,
|
|
105
|
+
q - default, dq, last action, [cos, sin] of each foot's gait phase.
|
|
106
|
+
"""
|
|
107
|
+
decimation = round(ctrl_dt / physics_dt)
|
|
108
|
+
if not math.isclose(decimation * physics_dt, ctrl_dt):
|
|
109
|
+
raise ValueError("ctrl_dt is not a whole number of physics steps")
|
|
110
|
+
return PolicySpec(
|
|
111
|
+
joints=list(joints),
|
|
112
|
+
actuators=list(actuators),
|
|
113
|
+
default_pose=list(default_pose),
|
|
114
|
+
action_scale=action_scale,
|
|
115
|
+
decimation=decimation,
|
|
116
|
+
first_tick=decimation - 1, # sim2sim: counter += 1, act when counter % n == 0
|
|
117
|
+
obs=[
|
|
118
|
+
ObsTerm("sensor", linvel_sensor),
|
|
119
|
+
ObsTerm("sensor", gyro_sensor),
|
|
120
|
+
ObsTerm("gravity", imu_site),
|
|
121
|
+
ObsTerm("command"),
|
|
122
|
+
ObsTerm("joint_pos"),
|
|
123
|
+
ObsTerm("joint_vel"),
|
|
124
|
+
ObsTerm("last_action"),
|
|
125
|
+
ObsTerm("phase"),
|
|
126
|
+
],
|
|
127
|
+
gait_hz=gait_hz,
|
|
128
|
+
gait_offsets=list(gait_offsets),
|
|
129
|
+
phase_order="cos_sin",
|
|
130
|
+
actuation=actuation,
|
|
131
|
+
kp=list(kp),
|
|
132
|
+
kd=list(kd),
|
|
133
|
+
)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""The producer and per-trial halves of livingproof-observation-binding/1.0.0 (#28).
|
|
3
|
+
|
|
4
|
+
The format and the hallway terms are livingproof-evaluator's (v1.6.0). This module says which
|
|
5
|
+
MCAP channel and fields of this simulator's recording carry each term, and merges that with the
|
|
6
|
+
robot's own entries into the per-trial binding written next to the recording. The producer binding
|
|
7
|
+
is the same for every robot (G1, Go1, T1); the robot supplies only what only it knows: the base
|
|
8
|
+
body and the nominal base height.
|
|
9
|
+
|
|
10
|
+
An observable is bound only when the producer carries it and the robot supplies what it needs.
|
|
11
|
+
Anything else is unbound, with the evaluator's reason, and is never guessed.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
FORMAT = "livingproof-observation-binding/1.0.0"
|
|
17
|
+
PRODUCER_ID = "livingproof-sim-mujoco"
|
|
18
|
+
# The vocabulary's terms, in its order (livingproof-evaluator examples/vocabulary/hallway).
|
|
19
|
+
TERMS = ["base", "base_height", "body_contact"]
|
|
20
|
+
POSE_TOPIC = "/base_pose"
|
|
21
|
+
POSE_SCHEMA_NAME = "foxglove.PoseInFrame"
|
|
22
|
+
CONTACT_TOPIC = "/wall_contacts"
|
|
23
|
+
CONTACT_SCHEMA_NAME = "livingproof.WallContact"
|
|
24
|
+
PRODUCER_MISSING = "producer-does-not-carry"
|
|
25
|
+
ROBOT_MISSING = "robot-entry-missing"
|
|
26
|
+
# What a robot must supply for an observable, besides the producer's channel.
|
|
27
|
+
_ROBOT_NEEDS = {"base": ("body",), "base_height": ("nominal",), "body_contact": ()}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _channel(topic: str, schema: str, fields: dict) -> dict:
|
|
31
|
+
return {
|
|
32
|
+
"topic": topic,
|
|
33
|
+
"encoding": "json",
|
|
34
|
+
"schema": schema,
|
|
35
|
+
"fields": fields,
|
|
36
|
+
"frame": "world",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def producer_binding() -> dict:
|
|
41
|
+
"""Which channels carry which terms. Shared across robots."""
|
|
42
|
+
return {
|
|
43
|
+
"format": FORMAT,
|
|
44
|
+
"kind": "producer",
|
|
45
|
+
"producer": {"id": PRODUCER_ID},
|
|
46
|
+
"observables": {
|
|
47
|
+
"base": _channel(
|
|
48
|
+
POSE_TOPIC,
|
|
49
|
+
POSE_SCHEMA_NAME,
|
|
50
|
+
{"x": "pose.position.x", "y": "pose.position.y"},
|
|
51
|
+
),
|
|
52
|
+
"base_height": _channel(POSE_TOPIC, POSE_SCHEMA_NAME, {"z": "pose.position.z"}),
|
|
53
|
+
# One message per contact event: {wall, start, end, depth}.
|
|
54
|
+
"body_contact": _channel(
|
|
55
|
+
CONTACT_TOPIC,
|
|
56
|
+
CONTACT_SCHEMA_NAME,
|
|
57
|
+
{"wall": "wall", "start": "start", "end": "end", "depth": "depth"},
|
|
58
|
+
),
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def nominal_from(configuration: dict, ref: str) -> dict | None:
|
|
64
|
+
"""The configuration's nominal base height as a binding nominal, or None when it has none.
|
|
65
|
+
|
|
66
|
+
The binding states meters; a configuration in another unit, or with a value that is not a
|
|
67
|
+
positive number, offers no nominal rather than a converted or guessed one. The source is the
|
|
68
|
+
configuration's own account of the value (measured, published, chosen, ...), carried as is:
|
|
69
|
+
a nominal whose configuration states no source is not offered, because the binding's source
|
|
70
|
+
is required and nothing here may claim one. `ref` is the caller's pinned revision of the file.
|
|
71
|
+
"""
|
|
72
|
+
locomotion = configuration.get("locomotion") if isinstance(configuration, dict) else None
|
|
73
|
+
nominal = locomotion.get("nominal_base_height") if isinstance(locomotion, dict) else None
|
|
74
|
+
if not isinstance(nominal, dict) or nominal.get("unit") != "m":
|
|
75
|
+
return None
|
|
76
|
+
value = nominal.get("value")
|
|
77
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
|
|
78
|
+
return None
|
|
79
|
+
source = nominal.get("source")
|
|
80
|
+
if not isinstance(source, str) or not source.strip():
|
|
81
|
+
return None
|
|
82
|
+
return {"value": value, "unit": "meters", "source": source, "ref": ref}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def robot_binding(robot_id: str, configuration: str, base_body: str, nominal: dict | None) -> dict:
|
|
86
|
+
"""What only the robot knows: its base body and, when it has one, its nominal."""
|
|
87
|
+
observables: dict = {"base": {"body": base_body}}
|
|
88
|
+
if nominal is not None:
|
|
89
|
+
observables["base_height"] = {"nominal": nominal}
|
|
90
|
+
return {
|
|
91
|
+
"format": FORMAT,
|
|
92
|
+
"kind": "robot",
|
|
93
|
+
"robot": {"id": robot_id},
|
|
94
|
+
"configuration": configuration,
|
|
95
|
+
"observables": observables,
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def merge(robot: dict, producer: dict, trial_id: str, recording: dict) -> dict:
|
|
100
|
+
"""The per-trial binding, in the vocabulary's order (the evaluator's reference rules)."""
|
|
101
|
+
observables: dict = {}
|
|
102
|
+
unbound: list = []
|
|
103
|
+
for term in TERMS:
|
|
104
|
+
carried = producer["observables"].get(term)
|
|
105
|
+
supplied = robot["observables"].get(term, {})
|
|
106
|
+
if carried is None:
|
|
107
|
+
unbound.append({"id": term, "reason": PRODUCER_MISSING})
|
|
108
|
+
elif any(need not in supplied for need in _ROBOT_NEEDS[term]):
|
|
109
|
+
unbound.append({"id": term, "reason": ROBOT_MISSING})
|
|
110
|
+
else:
|
|
111
|
+
observables[term] = {**carried, **supplied}
|
|
112
|
+
return {
|
|
113
|
+
"format": FORMAT,
|
|
114
|
+
"kind": "merged",
|
|
115
|
+
"trial_id": trial_id,
|
|
116
|
+
"robot": {"id": robot["robot"]["id"], "configuration": robot["configuration"]},
|
|
117
|
+
"producer": {"id": producer["producer"]["id"]},
|
|
118
|
+
"recording": recording,
|
|
119
|
+
"observables": observables,
|
|
120
|
+
"bound_observables": list(observables),
|
|
121
|
+
"unbound": unbound,
|
|
122
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""MuJoCo-native headless execution, with an outer process deadline."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import multiprocessing as mp
|
|
8
|
+
import signal
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from importlib.metadata import version
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from livingproof_common.versioning import Consumer, current_version
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def identity():
|
|
18
|
+
display, package, source = current_version(
|
|
19
|
+
Consumer("livingproof-sim-mujoco", Path(__file__).parent)
|
|
20
|
+
)
|
|
21
|
+
return {
|
|
22
|
+
"version": display,
|
|
23
|
+
"package_version": package,
|
|
24
|
+
"provenance": source,
|
|
25
|
+
"mujoco": version("mujoco"),
|
|
26
|
+
"livingproof_common": version("livingproof-common"),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def positive_int(value):
|
|
31
|
+
try:
|
|
32
|
+
result = int(value)
|
|
33
|
+
if result > 0:
|
|
34
|
+
return result
|
|
35
|
+
except ValueError:
|
|
36
|
+
pass
|
|
37
|
+
raise argparse.ArgumentTypeError("expected a positive integer, for example --steps 100")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def positive_seconds(value):
|
|
41
|
+
try:
|
|
42
|
+
result = float(value)
|
|
43
|
+
if math.isfinite(result) and result > 0:
|
|
44
|
+
return result
|
|
45
|
+
except ValueError:
|
|
46
|
+
pass
|
|
47
|
+
raise argparse.ArgumentTypeError("expected finite positive seconds, for example --timeout 10")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parser():
|
|
51
|
+
p = argparse.ArgumentParser(
|
|
52
|
+
prog="livingproof-sim-mujoco",
|
|
53
|
+
description="Load an MJCF XML or compiled MJB model and advance native MuJoCo physics.",
|
|
54
|
+
epilog="Example: livingproof-sim-mujoco --model builtin:falling --steps 100 --headless. "
|
|
55
|
+
"Outputs one JSON result. Exit 0: requested steps completed; 2: input/engine error; "
|
|
56
|
+
"124: wall timeout; 130/143: SIGINT/SIGTERM. Physics execution is not a robot "
|
|
57
|
+
"capability PASS. Use --version for engine and build provenance.",
|
|
58
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
59
|
+
)
|
|
60
|
+
p.add_argument(
|
|
61
|
+
"--model",
|
|
62
|
+
default="builtin:falling",
|
|
63
|
+
help="MJCF .xml or MJB .mjb path; includes resolve relative to XML; or builtin:falling",
|
|
64
|
+
)
|
|
65
|
+
p.add_argument(
|
|
66
|
+
"--steps", type=positive_int, default=100, help="maximum number of mj_step calls"
|
|
67
|
+
)
|
|
68
|
+
p.add_argument(
|
|
69
|
+
"--timeout",
|
|
70
|
+
type=positive_seconds,
|
|
71
|
+
default=10.0,
|
|
72
|
+
help="wall seconds including worker startup/model loading; shutdown grace is at most 2 additional seconds",
|
|
73
|
+
)
|
|
74
|
+
p.add_argument(
|
|
75
|
+
"--headless",
|
|
76
|
+
action="store_true",
|
|
77
|
+
default=True,
|
|
78
|
+
help="run without viewer or graphics context (the only supported mode)",
|
|
79
|
+
)
|
|
80
|
+
p.add_argument(
|
|
81
|
+
"--version",
|
|
82
|
+
action="store_true",
|
|
83
|
+
help="print tool, shared-library and engine versions as JSON, then exit",
|
|
84
|
+
)
|
|
85
|
+
return p
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def worker(connection, stop, model_path, steps):
|
|
89
|
+
# The supervisor owns signal semantics, including during native model loading.
|
|
90
|
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
91
|
+
try:
|
|
92
|
+
import mujoco
|
|
93
|
+
import numpy as np
|
|
94
|
+
|
|
95
|
+
# This callback is process-global; each worker owns one model and exits.
|
|
96
|
+
warnings = []
|
|
97
|
+
|
|
98
|
+
def record_warning(message):
|
|
99
|
+
if not warnings:
|
|
100
|
+
warnings.append(str(message)[:2000])
|
|
101
|
+
|
|
102
|
+
mujoco.set_mju_user_warning(record_warning)
|
|
103
|
+
path = Path(model_path)
|
|
104
|
+
model = (
|
|
105
|
+
mujoco.MjModel.from_binary_path(str(path))
|
|
106
|
+
if path.suffix.lower() == ".mjb"
|
|
107
|
+
else mujoco.MjModel.from_xml_path(str(path))
|
|
108
|
+
)
|
|
109
|
+
if not math.isfinite(model.opt.timestep) or model.opt.timestep <= 0:
|
|
110
|
+
raise ValueError("MuJoCo model timestep must be finite and positive")
|
|
111
|
+
if warnings:
|
|
112
|
+
raise ValueError(f"MuJoCo model loading warning: {warnings[0]}")
|
|
113
|
+
data = mujoco.MjData(model)
|
|
114
|
+
if not np.isfinite(data.qpos).all():
|
|
115
|
+
raise ValueError("MuJoCo model has non-finite initial positions")
|
|
116
|
+
initial = data.qpos[:16].tolist()
|
|
117
|
+
connection.send(
|
|
118
|
+
{
|
|
119
|
+
"event": "loaded",
|
|
120
|
+
"nq": model.nq,
|
|
121
|
+
"nv": model.nv,
|
|
122
|
+
"timestep": model.opt.timestep,
|
|
123
|
+
"engine": mujoco.mj_versionString(),
|
|
124
|
+
}
|
|
125
|
+
)
|
|
126
|
+
completed = 0
|
|
127
|
+
while completed < steps and not stop.is_set():
|
|
128
|
+
before = data.time
|
|
129
|
+
mujoco.mj_step(model, data)
|
|
130
|
+
completed += 1
|
|
131
|
+
if warnings:
|
|
132
|
+
raise ValueError(f"MuJoCo execution warning: {warnings[0]}")
|
|
133
|
+
if (
|
|
134
|
+
not np.isfinite(data.qpos).all()
|
|
135
|
+
or not np.isfinite(data.qvel).all()
|
|
136
|
+
or not math.isfinite(data.time)
|
|
137
|
+
or data.time <= before
|
|
138
|
+
or any(w.number for w in data.warning)
|
|
139
|
+
):
|
|
140
|
+
raise ValueError(
|
|
141
|
+
"MuJoCo reported a warning, non-finite state, or non-advancing time"
|
|
142
|
+
)
|
|
143
|
+
connection.send(
|
|
144
|
+
{
|
|
145
|
+
"event": "result",
|
|
146
|
+
"status": "completed" if completed == steps else "interrupted",
|
|
147
|
+
"steps": completed,
|
|
148
|
+
"simulation_time": data.time,
|
|
149
|
+
"initial_qpos": initial,
|
|
150
|
+
"final_qpos": data.qpos[:16].tolist(),
|
|
151
|
+
"qpos_truncated": model.nq > 16,
|
|
152
|
+
}
|
|
153
|
+
)
|
|
154
|
+
except Exception as exc:
|
|
155
|
+
connection.send(
|
|
156
|
+
{
|
|
157
|
+
"event": "result",
|
|
158
|
+
"status": "error",
|
|
159
|
+
"diagnostic": str(exc)[:2000],
|
|
160
|
+
"hint": "Check the MJCF/MJB model and its assets; try --model builtin:falling --steps 100.",
|
|
161
|
+
}
|
|
162
|
+
)
|
|
163
|
+
finally:
|
|
164
|
+
connection.close()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def run(args):
|
|
168
|
+
path = (
|
|
169
|
+
Path(__file__).parent / "models/falling.xml"
|
|
170
|
+
if args.model == "builtin:falling"
|
|
171
|
+
else Path(args.model)
|
|
172
|
+
)
|
|
173
|
+
if path.suffix.lower() not in {".xml", ".mjb"} or not path.is_file():
|
|
174
|
+
print(
|
|
175
|
+
"Expected an existing .xml/.mjb model or builtin:falling. "
|
|
176
|
+
"Try: livingproof-sim-mujoco --model builtin:falling --steps 100",
|
|
177
|
+
file=sys.stderr,
|
|
178
|
+
)
|
|
179
|
+
return 2
|
|
180
|
+
ctx = mp.get_context("spawn")
|
|
181
|
+
receive, send = ctx.Pipe(duplex=False)
|
|
182
|
+
stop = ctx.Event()
|
|
183
|
+
process = ctx.Process(target=worker, args=(send, stop, str(path.resolve()), args.steps))
|
|
184
|
+
received_signal = []
|
|
185
|
+
previous = {}
|
|
186
|
+
for signum in (signal.SIGINT, signal.SIGTERM):
|
|
187
|
+
previous[signum] = signal.signal(
|
|
188
|
+
signum, lambda signum, frame: received_signal.append(signum)
|
|
189
|
+
)
|
|
190
|
+
start = time.monotonic()
|
|
191
|
+
result = None
|
|
192
|
+
loaded = None
|
|
193
|
+
reason = None
|
|
194
|
+
try:
|
|
195
|
+
process.start()
|
|
196
|
+
send.close()
|
|
197
|
+
while True:
|
|
198
|
+
if received_signal:
|
|
199
|
+
reason = "signal"
|
|
200
|
+
break
|
|
201
|
+
if time.monotonic() - start >= args.timeout:
|
|
202
|
+
reason = "timeout"
|
|
203
|
+
break
|
|
204
|
+
if receive.poll(0.01):
|
|
205
|
+
try:
|
|
206
|
+
message = receive.recv()
|
|
207
|
+
except EOFError:
|
|
208
|
+
break
|
|
209
|
+
if message["event"] == "loaded":
|
|
210
|
+
loaded = message
|
|
211
|
+
print("MuJoCo model loaded; stepping headlessly", file=sys.stderr, flush=True)
|
|
212
|
+
else:
|
|
213
|
+
result = message
|
|
214
|
+
break
|
|
215
|
+
if not process.is_alive() and not receive.poll():
|
|
216
|
+
break
|
|
217
|
+
stop.set()
|
|
218
|
+
process.join(1)
|
|
219
|
+
if process.is_alive():
|
|
220
|
+
process.terminate()
|
|
221
|
+
process.join(0.5)
|
|
222
|
+
if process.is_alive():
|
|
223
|
+
process.kill()
|
|
224
|
+
process.join(0.5)
|
|
225
|
+
if result is None and receive.poll():
|
|
226
|
+
try:
|
|
227
|
+
message = receive.recv()
|
|
228
|
+
if message["event"] == "result":
|
|
229
|
+
result = message
|
|
230
|
+
except EOFError:
|
|
231
|
+
pass
|
|
232
|
+
result = result or {
|
|
233
|
+
"status": "error",
|
|
234
|
+
"diagnostic": "Worker exited before returning physics results",
|
|
235
|
+
}
|
|
236
|
+
if reason:
|
|
237
|
+
result["status"] = reason
|
|
238
|
+
result.update(
|
|
239
|
+
model=args.model,
|
|
240
|
+
requested_steps=args.steps,
|
|
241
|
+
loaded=loaded,
|
|
242
|
+
identity=identity(),
|
|
243
|
+
worker_exitcode=process.exitcode,
|
|
244
|
+
wall_seconds=time.monotonic() - start,
|
|
245
|
+
evidence="physics-execution-only",
|
|
246
|
+
)
|
|
247
|
+
print(json.dumps(result, sort_keys=True, allow_nan=False))
|
|
248
|
+
if reason == "signal":
|
|
249
|
+
return 128 + received_signal[0]
|
|
250
|
+
if reason == "timeout":
|
|
251
|
+
return 124
|
|
252
|
+
return 0 if result["status"] == "completed" and process.exitcode == 0 else 2
|
|
253
|
+
finally:
|
|
254
|
+
if process.is_alive():
|
|
255
|
+
process.kill()
|
|
256
|
+
process.join(0.5)
|
|
257
|
+
receive.close()
|
|
258
|
+
send.close()
|
|
259
|
+
for signum, handler in previous.items():
|
|
260
|
+
signal.signal(signum, handler)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def main():
|
|
264
|
+
args = parser().parse_args()
|
|
265
|
+
if args.version:
|
|
266
|
+
print(json.dumps(identity(), sort_keys=True))
|
|
267
|
+
return 0
|
|
268
|
+
return run(args)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
sys.exit(main())
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Frozen hallway scenario: names, the tagged parameter file, and recorded rounding.
|
|
3
|
+
|
|
4
|
+
This is the compatibility module for scenario ids. Generic modules do not name
|
|
5
|
+
the scenario or the world. The parameter file is the byte copy of
|
|
6
|
+
robot-capability-specs v2.3.0 ``specs/scenarios/walk-hallway/parameters.json``
|
|
7
|
+
(commit 57317e617014a6df97bb7fba9d92a890af8d42e5). The bytes match v2.2.0. It is the last resort when
|
|
8
|
+
the verification lock and the robot pins do not carry the file.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
PARAMETERS_SHA256 = "9226aa6bc0e577863bdc210514e7e7c3a7edc32f49c4f7b46aa7249837f08b3d"
|
|
18
|
+
PARAMETERS_TAG = "v2.3.0"
|
|
19
|
+
PARAMETERS_COMMIT = "57317e617014a6df97bb7fba9d92a890af8d42e5"
|
|
20
|
+
SCENARIO = "walk-hallway@0.1.0"
|
|
21
|
+
EXIT, SPAWN = "exit", "spawn-entrance"
|
|
22
|
+
# Pins path used when a robot lock does not name a world id and version.
|
|
23
|
+
FROZEN_WORLD_PATH = "worlds/hallway-open/0.1.0/world.json"
|
|
24
|
+
WORLD_FORMAT_0_1 = "livingproof-world/0.1"
|
|
25
|
+
WORLD_FORMAT_0_2 = "livingproof-world/0.2"
|
|
26
|
+
_PATH = Path(__file__).with_name("parameters.json")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parameters_document() -> dict:
|
|
30
|
+
"""The tagged parameter file. A sha256 mismatch is a test-system error."""
|
|
31
|
+
raw = _PATH.read_bytes()
|
|
32
|
+
digest = hashlib.sha256(raw).hexdigest()
|
|
33
|
+
if digest != PARAMETERS_SHA256:
|
|
34
|
+
raise RuntimeError(
|
|
35
|
+
f"ERROR: vendored parameter file sha256 {digest} != {PARAMETERS_SHA256} "
|
|
36
|
+
f"({PARAMETERS_TAG} {PARAMETERS_COMMIT}). "
|
|
37
|
+
"Restore compat/parameters.json from that tag."
|
|
38
|
+
)
|
|
39
|
+
return json.loads(raw)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_DOCUMENT = parameters_document()
|
|
43
|
+
COMMAND_SPEED = _DOCUMENT["parameters"]["command_speed"]["value"]
|
|
44
|
+
WALL_CLEARANCE = _DOCUMENT["parameters"]["wall_clearance"]["values"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def evidence_run_id(scenario: str, robot_id: str, configuration: str, created) -> str:
|
|
48
|
+
"""Run id. The frozen scenario keeps its historical prefix."""
|
|
49
|
+
if isinstance(scenario, str) and scenario.startswith("walk-hallway@"):
|
|
50
|
+
head = "walk-hallway"
|
|
51
|
+
elif isinstance(scenario, str) and "@" in scenario:
|
|
52
|
+
head = scenario.split("@", 1)[0]
|
|
53
|
+
else:
|
|
54
|
+
head = "scenario"
|
|
55
|
+
return f"{head}-{robot_id}-{configuration}-{created:%Y%m%dT%H%M%SZ}"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def recorded_limit(document: dict, name: str, raw_value: float, spec_value: float) -> float:
|
|
59
|
+
"""Value stored on a frozen hallway record.
|
|
60
|
+
|
|
61
|
+
``time_limit`` stays unrounded and ``lateral_limit`` stays at 6 decimal
|
|
62
|
+
places, which is what hallway evidence already records. Any other scenario
|
|
63
|
+
stores the spec-rounded value from ``resolve``.
|
|
64
|
+
"""
|
|
65
|
+
scenario = document.get("scenario") if isinstance(document, dict) else None
|
|
66
|
+
frozen = (
|
|
67
|
+
isinstance(scenario, dict)
|
|
68
|
+
and scenario.get("id") == "walk-hallway"
|
|
69
|
+
and scenario.get("revision") == "0.1.0"
|
|
70
|
+
)
|
|
71
|
+
if frozen and name == "time_limit":
|
|
72
|
+
return raw_value
|
|
73
|
+
if frozen and name == "lateral_limit":
|
|
74
|
+
return round(float(raw_value), 6)
|
|
75
|
+
return spec_value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def unsupported_world(world: dict) -> str | None:
|
|
79
|
+
"""ERROR text when this release cannot record the world, else None.
|
|
80
|
+
|
|
81
|
+
Format 0.2 needs a neutral observation writer. This release does not have
|
|
82
|
+
one, and the frozen hallway writer must not emit its format for that world.
|
|
83
|
+
"""
|
|
84
|
+
if not isinstance(world, dict):
|
|
85
|
+
return None
|
|
86
|
+
if world.get("format") != WORLD_FORMAT_0_2:
|
|
87
|
+
return None
|
|
88
|
+
ident = f"{world.get('id')!r} {world.get('content_version')!r}"
|
|
89
|
+
return (
|
|
90
|
+
"ERROR: world format livingproof-world/0.2 has no observation writer yet "
|
|
91
|
+
f"({ident}). The frozen hallway observation format stays on format 0.1 worlds. "
|
|
92
|
+
"A neutral format for 0.2 worlds is not in this release, so nothing was written. "
|
|
93
|
+
"Example: record a livingproof-world/0.1 world, such as the pinned open hallway."
|
|
94
|
+
)
|