simbridge-cad-mujoco 0.3.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.
- simbridge/__init__.py +3 -0
- simbridge/__main__.py +3 -0
- simbridge/articulation/__init__.py +0 -0
- simbridge/articulation/infer.py +44 -0
- simbridge/benchmark.py +163 -0
- simbridge/cli.py +104 -0
- simbridge/compile/__init__.py +0 -0
- simbridge/compile/mjcf.py +93 -0
- simbridge/diagnostics.py +26 -0
- simbridge/dynamics/__init__.py +0 -0
- simbridge/dynamics/inertia.py +41 -0
- simbridge/errors.py +2 -0
- simbridge/geometry/__init__.py +0 -0
- simbridge/geometry/adaptive.py +231 -0
- simbridge/geometry/clearance.py +159 -0
- simbridge/geometry/corridor.py +138 -0
- simbridge/geometry/meshes.py +84 -0
- simbridge/guided.py +112 -0
- simbridge/ingest/__init__.py +0 -0
- simbridge/ingest/step.py +182 -0
- simbridge/ir/__init__.py +0 -0
- simbridge/ir/schema.py +198 -0
- simbridge/onboarding.py +50 -0
- simbridge/pipeline.py +124 -0
- simbridge/validate/__init__.py +0 -0
- simbridge/validate/physics.py +222 -0
- simbridge/web/app.js +29 -0
- simbridge/web/index.html +17 -0
- simbridge/web/style.css +1 -0
- simbridge/webapp.py +250 -0
- simbridge_cad_mujoco-0.3.0.dist-info/METADATA +186 -0
- simbridge_cad_mujoco-0.3.0.dist-info/RECORD +36 -0
- simbridge_cad_mujoco-0.3.0.dist-info/WHEEL +5 -0
- simbridge_cad_mujoco-0.3.0.dist-info/entry_points.txt +2 -0
- simbridge_cad_mujoco-0.3.0.dist-info/licenses/LICENSE +21 -0
- simbridge_cad_mujoco-0.3.0.dist-info/top_level.txt +1 -0
simbridge/__init__.py
ADDED
simbridge/__main__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Rank geometric hints for review; never assign joints from these hints."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from OCP.BRepAdaptor import BRepAdaptor_Surface
|
|
4
|
+
from OCP.GeomAbs import GeomAbs_Cylinder
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def candidates(instances):
|
|
8
|
+
cylinders = []
|
|
9
|
+
for part in instances:
|
|
10
|
+
for face in part.shape.Faces():
|
|
11
|
+
surface = BRepAdaptor_Surface(face.wrapped)
|
|
12
|
+
if surface.GetType() != GeomAbs_Cylinder:
|
|
13
|
+
continue
|
|
14
|
+
cylinder = surface.Cylinder()
|
|
15
|
+
axis = cylinder.Axis()
|
|
16
|
+
point = np.array(axis.Location().Coord()) * 1e-3
|
|
17
|
+
direction = np.array(axis.Direction().Coord())
|
|
18
|
+
rotation, translation = part.transform[:3, :3], part.transform[:3, 3]
|
|
19
|
+
direction = rotation @ direction
|
|
20
|
+
point = rotation @ point + translation
|
|
21
|
+
cylinders.append((part, point, direction, cylinder.Radius() * 1e-3))
|
|
22
|
+
hints = []
|
|
23
|
+
seen = set()
|
|
24
|
+
for i, (a, point_a, axis_a, radius_a) in enumerate(cylinders):
|
|
25
|
+
for b, point_b, axis_b, radius_b in cylinders[i + 1:]:
|
|
26
|
+
if a.id == b.id or abs(axis_a @ axis_b) < np.cos(np.deg2rad(1)):
|
|
27
|
+
continue
|
|
28
|
+
offset = np.linalg.norm(np.cross(point_b - point_a, axis_a))
|
|
29
|
+
if offset > 1e-4:
|
|
30
|
+
continue
|
|
31
|
+
key = (a.id, b.id, tuple(np.round(axis_a, 4)))
|
|
32
|
+
if key in seen:
|
|
33
|
+
continue
|
|
34
|
+
seen.add(key)
|
|
35
|
+
hints.append({
|
|
36
|
+
"parts": [a.id, b.id], "axis_world": axis_a.tolist(),
|
|
37
|
+
"point_world_m": point_a.tolist(),
|
|
38
|
+
"evidence": "coaxial cylindrical surfaces; articulation and engagement unverified",
|
|
39
|
+
"radial_gap_m": abs(radius_a - radius_b),
|
|
40
|
+
"score": float(1 / (1 + abs(radius_a - radius_b) / 1e-4)),
|
|
41
|
+
"confidence": "low", "requires_confirmation": True,
|
|
42
|
+
"possible_types": ["revolute", "prismatic", "fixed"],
|
|
43
|
+
})
|
|
44
|
+
return sorted(hints, key=lambda h: -h["score"])
|
simbridge/benchmark.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""A bounded pilot experiment, not a population-level CAD benchmark.
|
|
2
|
+
|
|
3
|
+
Artifact mutations retain a frozen IR oracle. The correlated-input probe
|
|
4
|
+
deliberately alters the oracle too, exposing the limit of self-consistency.
|
|
5
|
+
"""
|
|
6
|
+
import csv
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import shutil
|
|
10
|
+
import time
|
|
11
|
+
import xml.etree.ElementTree as ET
|
|
12
|
+
|
|
13
|
+
import mujoco
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from simbridge.errors import SimBridgeError
|
|
17
|
+
from simbridge.onboarding import environment
|
|
18
|
+
from simbridge.pipeline import convert, digest, write_json
|
|
19
|
+
from simbridge.validate.physics import validate_model
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _set_scaled(element, attr, factor):
|
|
23
|
+
element.set(attr, " ".join(str(float(v) * factor) for v in element.get(attr).split()))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def benchmark(step, config, output, *, repeats=3, seeds=(0, 1, 2)):
|
|
27
|
+
if repeats < 1 or not seeds or any(seed < 0 for seed in seeds):
|
|
28
|
+
raise SimBridgeError("benchmark requires repeats >= 1 and nonnegative seeds")
|
|
29
|
+
output = Path(output)
|
|
30
|
+
if output.exists() and any(output.iterdir()):
|
|
31
|
+
raise SimBridgeError("benchmark output must be empty/new")
|
|
32
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
runtimes, clean_runs = [], []
|
|
34
|
+
base, robot = None, None
|
|
35
|
+
for repeat in range(repeats):
|
|
36
|
+
for seed in seeds:
|
|
37
|
+
folder = output / "conversions" / f"repeat-{repeat}-seed-{seed}"
|
|
38
|
+
current_robot, report = convert(step, config, folder, seed=seed)
|
|
39
|
+
if base is None:
|
|
40
|
+
base, robot = folder, current_robot
|
|
41
|
+
runtimes.append(report["conversion"]["seconds"])
|
|
42
|
+
clean_runs.append({"repeat": repeat, "seed": seed, "passed": report["passed"],
|
|
43
|
+
"seconds": report["conversion"]["seconds"], "errors": report["errors"]})
|
|
44
|
+
if not all(run["passed"] for run in clean_runs):
|
|
45
|
+
raise SimBridgeError("clean fixture did not pass; inspect conversions before applying fault probes")
|
|
46
|
+
tree = ET.parse(base / "model.xml")
|
|
47
|
+
bodies = tree.findall(".//body")
|
|
48
|
+
joints = tree.findall(".//joint")
|
|
49
|
+
motors = tree.findall("actuator/motor")
|
|
50
|
+
target_body = next((b for b in bodies if b.find("joint") is not None), bodies[-1])
|
|
51
|
+
body_name = target_body.get("name")
|
|
52
|
+
moving = next((l for l in robot.links if l.name == body_name), None)
|
|
53
|
+
probes = [("clean", "control")]
|
|
54
|
+
probes += [(name, "artifact_fault") for name in ["missing_asset", "body_translation", "mass_scale", "com_offset", "inertia_scale"]]
|
|
55
|
+
skipped = []
|
|
56
|
+
if joints:
|
|
57
|
+
probes += [(name, "artifact_fault") for name in ["axis_reversal", "joint_origin", "joint_limits"]]
|
|
58
|
+
else:
|
|
59
|
+
skipped += ["axis_reversal", "joint_origin", "joint_limits"]
|
|
60
|
+
if motors:
|
|
61
|
+
probes += [("motor_gear", "artifact_fault"), ("motor_bounds", "artifact_fault")]
|
|
62
|
+
else:
|
|
63
|
+
skipped += ["motor_gear", "motor_bounds"]
|
|
64
|
+
if len(motors) > 1:
|
|
65
|
+
probes.append(("motor_target", "artifact_fault"))
|
|
66
|
+
else:
|
|
67
|
+
skipped += ["motor_target"]
|
|
68
|
+
probes.append(("correlated_mass", "input_assumption_fault"))
|
|
69
|
+
rows = []
|
|
70
|
+
for name, group in probes:
|
|
71
|
+
folder = output / "probes" / name
|
|
72
|
+
shutil.copytree(base, folder)
|
|
73
|
+
xml_path = folder / "model.xml"
|
|
74
|
+
mutated = ET.parse(xml_path)
|
|
75
|
+
body = mutated.find(f".//body[@name='{body_name}']")
|
|
76
|
+
inertia = body.find("inertial")
|
|
77
|
+
oracle = robot.model_copy(deep=True)
|
|
78
|
+
if name == "missing_asset":
|
|
79
|
+
(folder / robot.links[0].assets.visual).unlink()
|
|
80
|
+
elif name == "body_translation":
|
|
81
|
+
position = [float(v) for v in body.get("pos").split()]
|
|
82
|
+
position[0] += 0.01
|
|
83
|
+
body.set("pos", " ".join(map(str, position)))
|
|
84
|
+
elif name in {"mass_scale", "correlated_mass"}:
|
|
85
|
+
_set_scaled(inertia, "mass", 2)
|
|
86
|
+
if name == "correlated_mass":
|
|
87
|
+
next(link for link in oracle.links if link.name == body_name).mass *= 2
|
|
88
|
+
elif name == "com_offset":
|
|
89
|
+
com = [float(v) for v in inertia.get("pos").split()]
|
|
90
|
+
com[0] += 0.01
|
|
91
|
+
inertia.set("pos", " ".join(map(str, com)))
|
|
92
|
+
elif name == "inertia_scale":
|
|
93
|
+
_set_scaled(inertia, "fullinertia", 2)
|
|
94
|
+
elif name == "axis_reversal":
|
|
95
|
+
_set_scaled(body.find("joint"), "axis", -1)
|
|
96
|
+
elif name == "joint_origin":
|
|
97
|
+
joint = body.find("joint")
|
|
98
|
+
point = np.asarray([float(v) for v in joint.get("pos").split()])
|
|
99
|
+
axis = np.asarray(moving.joint.axis)
|
|
100
|
+
perpendicular = np.cross(axis, [1, 0, 0])
|
|
101
|
+
if np.linalg.norm(perpendicular) < 0.5:
|
|
102
|
+
perpendicular = np.cross(axis, [0, 1, 0])
|
|
103
|
+
point += 0.01 * perpendicular / np.linalg.norm(perpendicular)
|
|
104
|
+
joint.set("pos", " ".join(map(str, point)))
|
|
105
|
+
elif name == "joint_limits":
|
|
106
|
+
_set_scaled(body.find("joint"), "range", 0.5)
|
|
107
|
+
elif name == "motor_gear":
|
|
108
|
+
_set_scaled(mutated.find("actuator/motor"), "gear", 2)
|
|
109
|
+
elif name == "motor_bounds":
|
|
110
|
+
_set_scaled(mutated.find("actuator/motor"), "ctrlrange", 2)
|
|
111
|
+
elif name == "motor_target":
|
|
112
|
+
motor_list = mutated.findall("actuator/motor")
|
|
113
|
+
motor_list[0].set("joint", motor_list[1].get("joint"))
|
|
114
|
+
mutated.write(xml_path)
|
|
115
|
+
write_json(folder / "robot.ir.json", oracle.model_dump(mode="json"))
|
|
116
|
+
# Remove the clean report so it cannot be mistaken for the mutated result.
|
|
117
|
+
(folder / "report.json").unlink()
|
|
118
|
+
(folder / "README.md").write_text("Controlled experiment: this is a mutated artifact, not a production model. See probe.json and the policy reports.\n")
|
|
119
|
+
write_json(folder / "probe.json", {"name": name, "group": group, "fault_present": name != "clean",
|
|
120
|
+
"oracle_corrupted": name == "correlated_mass"})
|
|
121
|
+
start = time.perf_counter()
|
|
122
|
+
compile_error = None
|
|
123
|
+
try:
|
|
124
|
+
mujoco.MjModel.from_xml_path(str(xml_path.resolve()))
|
|
125
|
+
except ValueError as exc:
|
|
126
|
+
compile_error = str(exc)
|
|
127
|
+
compile_time = time.perf_counter() - start
|
|
128
|
+
policies = [("compile_only", compile_error is None, [compile_error] if compile_error else [], compile_time)]
|
|
129
|
+
for policy, ir in [("without_reference", None), ("with_reference", oracle)]:
|
|
130
|
+
start = time.perf_counter()
|
|
131
|
+
report = validate_model(xml_path, ir=ir, seed=seeds[0])
|
|
132
|
+
duration = time.perf_counter() - start
|
|
133
|
+
write_json(folder / f"{policy}.json", report)
|
|
134
|
+
policies.append((policy, report["passed"], report["errors"], duration))
|
|
135
|
+
for policy, accepted, errors, seconds in policies:
|
|
136
|
+
rows.append({"probe": name, "group": group, "policy": policy, "fault_present": name != "clean",
|
|
137
|
+
"accepted": accepted, "seconds": seconds, "errors": errors})
|
|
138
|
+
metrics = {}
|
|
139
|
+
for policy in ["compile_only", "without_reference", "with_reference"]:
|
|
140
|
+
selected = [r for r in rows if r["policy"] == policy and r["group"] != "input_assumption_fault"]
|
|
141
|
+
tp = sum(r["fault_present"] and not r["accepted"] for r in selected)
|
|
142
|
+
fn = sum(r["fault_present"] and r["accepted"] for r in selected)
|
|
143
|
+
fp = sum(not r["fault_present"] and not r["accepted"] for r in selected)
|
|
144
|
+
tn = sum(not r["fault_present"] and r["accepted"] for r in selected)
|
|
145
|
+
metrics[policy] = {"detected_artifact_faults": tp, "missed_artifact_faults": fn,
|
|
146
|
+
"false_rejections": fp, "accepted_clean_controls": tn,
|
|
147
|
+
"artifact_fault_count": tp + fn}
|
|
148
|
+
summary = {"clean_runs": len(clean_runs), "clean_runs_passed": sum(r["passed"] for r in clean_runs),
|
|
149
|
+
"conversion_median_s": float(np.median(runtimes)), "conversion_p95_s": float(np.percentile(runtimes, 95)),
|
|
150
|
+
"policies": metrics, "skipped_probes": skipped,
|
|
151
|
+
"assumption_fault": [r for r in rows if r["group"] == "input_assumption_fault"],
|
|
152
|
+
"scope": "small deterministic artifact-mutation pilot; frozen IR is an oracle, not independent physical ground truth; correlated source errors may pass"}
|
|
153
|
+
result = {"schema_version": "1.0", "summary": summary, "environment": environment(),
|
|
154
|
+
"inputs": {"step_sha256": digest(step), "config_sha256": digest(config)},
|
|
155
|
+
"repeats": repeats, "seeds": list(seeds), "steps_per_run": 1000,
|
|
156
|
+
"timing_scope": "warm interpreter, includes ingestion/export/1000-step validation; excludes startup and human configuration",
|
|
157
|
+
"clean_runs": clean_runs, "probes": rows}
|
|
158
|
+
write_json(output / "results.json", result)
|
|
159
|
+
with (output / "probes.csv").open("w", newline="") as stream:
|
|
160
|
+
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
|
161
|
+
writer.writeheader()
|
|
162
|
+
writer.writerows({**r, "errors": json.dumps(r["errors"])} for r in rows)
|
|
163
|
+
return result
|
simbridge/cli.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Local CLI; no CAD cloud credentials or web service required."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None):
|
|
9
|
+
from simbridge import __version__
|
|
10
|
+
parser = argparse.ArgumentParser(prog="simbridge", description="STEP assemblies to validated MuJoCo models")
|
|
11
|
+
parser.add_argument("--version", action="version", version=f"simbridge {__version__}")
|
|
12
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
13
|
+
inspect = commands.add_parser("inspect", help="inspect STEP occurrence hierarchy, units and candidate axes")
|
|
14
|
+
inspect.add_argument("step", type=Path)
|
|
15
|
+
inspect.add_argument("--out", type=Path, default=Path("inspection.json"))
|
|
16
|
+
configure = commands.add_parser("configure", help="write an incomplete configuration template with exact part IDs")
|
|
17
|
+
configure.add_argument("step", type=Path)
|
|
18
|
+
configure.add_argument("--out", type=Path, required=True)
|
|
19
|
+
doctor = commands.add_parser("doctor", help="report Python/platform and installed dependency versions")
|
|
20
|
+
doctor.add_argument("--out", type=Path)
|
|
21
|
+
benchmark = commands.add_parser("benchmark", help="run repeated conversions and validator fault probes")
|
|
22
|
+
benchmark.add_argument("step", type=Path)
|
|
23
|
+
benchmark.add_argument("--config", type=Path, required=True)
|
|
24
|
+
benchmark.add_argument("--out", type=Path, required=True)
|
|
25
|
+
benchmark.add_argument("--repeats", type=int, default=3)
|
|
26
|
+
benchmark.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2])
|
|
27
|
+
convert = commands.add_parser("convert", help="compile STEP with explicit articulation and material metadata")
|
|
28
|
+
convert.add_argument("step", type=Path)
|
|
29
|
+
convert.add_argument("--config", type=Path, required=True)
|
|
30
|
+
convert.add_argument("--out", type=Path, required=True)
|
|
31
|
+
for cmd in [convert, commands.add_parser("validate", help="compile MJCF and run a deterministic physics check")]:
|
|
32
|
+
cmd.add_argument("--steps", type=int, default=1000)
|
|
33
|
+
cmd.add_argument("--seed", type=int, default=0)
|
|
34
|
+
validate = commands.choices["validate"]
|
|
35
|
+
validate.add_argument("model", type=Path)
|
|
36
|
+
validate.add_argument("--out", type=Path, default=Path("report.json"))
|
|
37
|
+
preview = commands.add_parser("preview", help="open the native MuJoCo viewer")
|
|
38
|
+
preview.add_argument("model", type=Path)
|
|
39
|
+
preview.add_argument("--duration", type=float, help="auto-close after this many seconds (macOS: use mjpython)")
|
|
40
|
+
serve = commands.add_parser("serve", help="open the local drag-and-drop CAD review app")
|
|
41
|
+
serve.add_argument("--port", type=int, default=8765)
|
|
42
|
+
serve.add_argument("--workspace", type=Path, default=Path("build/review"))
|
|
43
|
+
serve.add_argument("--no-browser", action="store_true")
|
|
44
|
+
args = parser.parse_args(argv)
|
|
45
|
+
try:
|
|
46
|
+
from simbridge.pipeline import write_json
|
|
47
|
+
if args.command == "configure":
|
|
48
|
+
from simbridge.onboarding import configuration_template
|
|
49
|
+
print(json.dumps(configuration_template(args.step, args.out), indent=2))
|
|
50
|
+
elif args.command == "doctor":
|
|
51
|
+
from simbridge.onboarding import environment
|
|
52
|
+
info = environment()
|
|
53
|
+
if args.out:
|
|
54
|
+
write_json(args.out, info)
|
|
55
|
+
print(json.dumps(info, indent=2))
|
|
56
|
+
elif args.command == "benchmark":
|
|
57
|
+
from simbridge.benchmark import benchmark
|
|
58
|
+
result = benchmark(args.step, args.config, args.out, repeats=args.repeats, seeds=args.seeds)
|
|
59
|
+
print(json.dumps(result["summary"], indent=2))
|
|
60
|
+
elif args.command == "inspect":
|
|
61
|
+
from simbridge.ingest.step import read_step
|
|
62
|
+
result = read_step(args.step, strict=False).inspection()
|
|
63
|
+
write_json(args.out, result)
|
|
64
|
+
print(f"Inspected {result['instance_count']} instances ({result['definition_count']} definitions) -> {args.out}")
|
|
65
|
+
elif args.command == "convert":
|
|
66
|
+
from simbridge.pipeline import convert
|
|
67
|
+
_, report = convert(args.step, args.config, args.out, steps=args.steps, seed=args.seed)
|
|
68
|
+
print(json.dumps({"passed": report["passed"], "output": str(args.out), "errors": report["errors"], "conversion": report["conversion"]}, indent=2))
|
|
69
|
+
return 0 if report["passed"] else 1
|
|
70
|
+
elif args.command == "validate":
|
|
71
|
+
from simbridge.validate.physics import validate_model
|
|
72
|
+
from simbridge.ir.schema import RobotIR
|
|
73
|
+
ir_path = args.model.parent / "robot.ir.json"
|
|
74
|
+
ir = RobotIR.model_validate_json(ir_path.read_text()) if ir_path.exists() else None
|
|
75
|
+
report = validate_model(args.model, ir=ir, steps=args.steps, seed=args.seed)
|
|
76
|
+
write_json(args.out, report)
|
|
77
|
+
print(json.dumps({"passed": report["passed"], "errors": report["errors"], "report": str(args.out)}, indent=2))
|
|
78
|
+
return 0 if report["passed"] else 1
|
|
79
|
+
elif args.command == "serve":
|
|
80
|
+
from simbridge.webapp import serve
|
|
81
|
+
serve(args.workspace, port=args.port, open_browser=not args.no_browser)
|
|
82
|
+
elif args.command == "preview":
|
|
83
|
+
import mujoco
|
|
84
|
+
import mujoco.viewer
|
|
85
|
+
import time
|
|
86
|
+
model = mujoco.MjModel.from_xml_path(str(args.model.resolve()))
|
|
87
|
+
if args.duration is not None and args.duration <= 0:
|
|
88
|
+
raise ValueError("preview duration must be positive")
|
|
89
|
+
data = mujoco.MjData(model)
|
|
90
|
+
with mujoco.viewer.launch_passive(model, data) as viewer:
|
|
91
|
+
end = time.monotonic() + args.duration if args.duration is not None else float("inf")
|
|
92
|
+
while viewer.is_running() and time.monotonic() < end:
|
|
93
|
+
start = time.monotonic()
|
|
94
|
+
mujoco.mj_step(model, data)
|
|
95
|
+
viewer.sync()
|
|
96
|
+
time.sleep(max(0, model.opt.timestep - (time.monotonic() - start)))
|
|
97
|
+
return 0
|
|
98
|
+
except (ValueError, OSError, RuntimeError) as exc:
|
|
99
|
+
print(f"simbridge: {exc}", file=sys.stderr)
|
|
100
|
+
return 2
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
raise SystemExit(main())
|
|
File without changes
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Deterministic nested-body MJCF with explicit centroidal inertias."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from itertools import product
|
|
4
|
+
import xml.etree.ElementTree as ET
|
|
5
|
+
|
|
6
|
+
import mujoco
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def numbers(values):
|
|
11
|
+
return " ".join(f"{float(v):.15g}" for v in np.asarray(values).ravel())
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def quaternion(rotation):
|
|
15
|
+
result = np.empty(4)
|
|
16
|
+
mujoco.mju_mat2Quat(result, np.asarray(rotation, dtype=float).ravel())
|
|
17
|
+
return result
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def compile_mjcf(robot, output_path):
|
|
21
|
+
root = ET.Element("mujoco", model=robot.name)
|
|
22
|
+
ET.SubElement(root, "compiler", angle="radian", autolimits="true", inertiafromgeom="false", fusestatic="false")
|
|
23
|
+
ET.SubElement(root, "option", timestep=numbers([robot.timestep]), gravity=numbers(robot.gravity), integrator="implicitfast")
|
|
24
|
+
corners = []
|
|
25
|
+
for link in robot.links:
|
|
26
|
+
center = np.asarray(link.assets.collision_center)
|
|
27
|
+
half_size = np.asarray(link.assets.collision_half_size)
|
|
28
|
+
transform = np.asarray(link.world_transform)
|
|
29
|
+
for signs in product([-1, 1], repeat=3):
|
|
30
|
+
point = center + half_size * signs
|
|
31
|
+
corners.append(transform[:3, :3] @ point + transform[:3, 3])
|
|
32
|
+
low, high = np.min(corners, axis=0), np.max(corners, axis=0)
|
|
33
|
+
ET.SubElement(root, "statistic", center=numbers((low + high) / 2), extent=numbers([max(np.linalg.norm(high - low), 0.01)]))
|
|
34
|
+
asset = ET.SubElement(root, "asset")
|
|
35
|
+
for link in robot.links:
|
|
36
|
+
ET.SubElement(asset, "mesh", name=f"{link.name}_visual", file=link.assets.visual)
|
|
37
|
+
if link.assets.collision_type == "convex_hull":
|
|
38
|
+
ET.SubElement(asset, "mesh", name=f"{link.name}_collision", file=link.assets.collision)
|
|
39
|
+
for index, path in enumerate(link.assets.collision_meshes):
|
|
40
|
+
ET.SubElement(asset, "mesh", name=f"{link.name}_collision_{index}", file=path)
|
|
41
|
+
world = ET.SubElement(root, "worldbody")
|
|
42
|
+
ET.SubElement(world, "light", pos="0 -1 2", dir="0 0 -1", directional="true")
|
|
43
|
+
by_name = {link.name: link for link in robot.links}
|
|
44
|
+
children = {}
|
|
45
|
+
for link in robot.links:
|
|
46
|
+
children.setdefault(link.parent, []).append(link)
|
|
47
|
+
|
|
48
|
+
def emit(link, element):
|
|
49
|
+
transform = np.asarray(link.world_transform)
|
|
50
|
+
relative = transform if link.parent is None else np.linalg.inv(np.asarray(by_name[link.parent].world_transform)) @ transform
|
|
51
|
+
body = ET.SubElement(element, "body", name=link.name, pos=numbers(relative[:3, 3]), quat=numbers(quaternion(relative[:3, :3])))
|
|
52
|
+
tensor = np.asarray(link.inertia)
|
|
53
|
+
ET.SubElement(body, "inertial", pos=numbers(link.com), mass=numbers([link.mass]),
|
|
54
|
+
fullinertia=numbers([tensor[0, 0], tensor[1, 1], tensor[2, 2], tensor[0, 1], tensor[0, 2], tensor[1, 2]]))
|
|
55
|
+
joint = link.joint
|
|
56
|
+
if joint.type != "fixed":
|
|
57
|
+
ET.SubElement(body, "joint", name=f"{link.name}_joint", type="hinge" if joint.type == "revolute" else "slide",
|
|
58
|
+
pos=numbers(joint.position), axis=numbers(joint.axis), range=numbers(joint.limits),
|
|
59
|
+
damping=numbers([joint.damping]), limited="true")
|
|
60
|
+
palette = ["0.18 0.32 0.44 1", "0.10 0.68 0.62 1", "0.95 0.56 0.21 1"]
|
|
61
|
+
color = palette[list(by_name).index(link.name) % len(palette)]
|
|
62
|
+
ET.SubElement(body, "geom", name=f"{link.name}_visual", type="mesh", mesh=f"{link.name}_visual",
|
|
63
|
+
contype="0", conaffinity="0", group="2", rgba=color, density="0")
|
|
64
|
+
attrs = dict(name=f"{link.name}_collision", group="3", rgba="1 0.3 0.1 0.25", density="0")
|
|
65
|
+
if link.assets.collision_type == "corridor":
|
|
66
|
+
for index, path in enumerate(link.assets.collision_meshes):
|
|
67
|
+
ET.SubElement(body, "geom", **(attrs | dict(name=f"{link.name}_collision_{index}", type="mesh",
|
|
68
|
+
mesh=f"{link.name}_collision_{index}")))
|
|
69
|
+
elif link.assets.collision_type == "adaptive":
|
|
70
|
+
for index, box in enumerate(link.assets.collision_boxes):
|
|
71
|
+
ET.SubElement(body, "geom", **(attrs | dict(name=f"{link.name}_collision_{index}", type="box",
|
|
72
|
+
size=numbers(box.half_size), pos=numbers(box.center))))
|
|
73
|
+
elif link.assets.collision_type == "box":
|
|
74
|
+
attrs.update(type="box", size=numbers(link.assets.collision_half_size), pos=numbers(link.assets.collision_center))
|
|
75
|
+
else:
|
|
76
|
+
attrs.update(type="mesh", mesh=f"{link.name}_collision")
|
|
77
|
+
if link.assets.collision_type not in {"adaptive", "corridor"}:
|
|
78
|
+
ET.SubElement(body, "geom", **attrs)
|
|
79
|
+
for child in children.get(link.name, []):
|
|
80
|
+
emit(child, body)
|
|
81
|
+
|
|
82
|
+
emit(children[None][0], world)
|
|
83
|
+
motors = [link for link in robot.links if link.joint.actuator]
|
|
84
|
+
if motors:
|
|
85
|
+
actuator = ET.SubElement(root, "actuator")
|
|
86
|
+
for link in motors:
|
|
87
|
+
settings = link.joint.actuator
|
|
88
|
+
ET.SubElement(actuator, "motor", name=f"{link.name}_motor", joint=f"{link.name}_joint",
|
|
89
|
+
gear=numbers([settings.gear]), ctrllimited="true", forcelimited="true",
|
|
90
|
+
ctrlrange=numbers([-settings.force_limit, settings.force_limit]),
|
|
91
|
+
forcerange=numbers([-settings.force_limit, settings.force_limit]))
|
|
92
|
+
ET.indent(root, space=" ")
|
|
93
|
+
Path(output_path).write_text(ET.tostring(root, encoding="unicode") + "\n")
|
simbridge/diagnostics.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Stable diagnostic categories supplement the human-readable report text."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def diagnostic(message, severity="error"):
|
|
5
|
+
rules = [
|
|
6
|
+
("missing asset", "ASSET_MISSING", "assets", "Restore the referenced asset or reconvert into a new directory."),
|
|
7
|
+
("compilation failed", "MJCF_COMPILE_FAILED", "compile", "Inspect the MuJoCo message and the generated model XML."),
|
|
8
|
+
("mismatch", "REFERENCE_MISMATCH", "reference", "Compare the compiled output with independently reviewed source metadata."),
|
|
9
|
+
("missing from compiled", "REFERENCE_MISMATCH", "reference", "Restore the expected body and its parent mapping."),
|
|
10
|
+
("initial collision penetration", "INITIAL_PENETRATION", "collision", "Review collision proxies and CAD placement; use multiple proxies for concave parts."),
|
|
11
|
+
("actuator direction", "ACTUATOR_MOTION_FAILED", "actuation", "Review the motor target, gear, control bounds and blocked motion."),
|
|
12
|
+
("nonfinite", "NONFINITE_STATE", "simulation", "Review masses, inertia, constraints, solver settings and excitation."),
|
|
13
|
+
("numerical warnings", "NUMERICAL_WARNING", "simulation", "Inspect the reported MuJoCo warning and model scales."),
|
|
14
|
+
("joint limit violation", "JOINT_LIMIT_VIOLATION", "simulation", "Review limits, load, damping and the declared overshoot tolerance."),
|
|
15
|
+
("time reset", "TIME_RESET", "simulation", "Inspect numerical instability and MuJoCo recovery."),
|
|
16
|
+
]
|
|
17
|
+
for text, code, stage, repair in rules:
|
|
18
|
+
if text in message.lower():
|
|
19
|
+
return {"code": code, "stage": stage, "severity": severity, "message": message, "suggested_repair": repair}
|
|
20
|
+
return {"code": "VALIDATION_ERROR" if severity == "error" else "MODEL_ASSUMPTION", "stage": "validation",
|
|
21
|
+
"severity": severity, "message": message, "suggested_repair": "Review the report and configuration."}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def add_diagnostics(report):
|
|
25
|
+
report["diagnostics"] = [diagnostic(m) for m in report["errors"]] + [diagnostic(m, "warning") for m in report["warnings"]]
|
|
26
|
+
return report
|
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Centroidal inertia in SI, never approximated from triangle meshes."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from simbridge.errors import SimBridgeError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def validate_inertia(mass, inertia):
|
|
8
|
+
tensor = np.asarray(inertia, dtype=float)
|
|
9
|
+
if not np.isfinite(mass) or mass <= 0:
|
|
10
|
+
raise SimBridgeError("mass must be finite and positive")
|
|
11
|
+
if tensor.shape != (3, 3) or not np.isfinite(tensor).all():
|
|
12
|
+
raise SimBridgeError("inertia must be a finite 3x3 tensor")
|
|
13
|
+
if not np.allclose(tensor, tensor.T, rtol=1e-9, atol=1e-16):
|
|
14
|
+
raise SimBridgeError("inertia must be symmetric")
|
|
15
|
+
principal = np.linalg.eigvalsh(tensor)
|
|
16
|
+
if principal[0] <= 0 or principal[2] > principal[0] + principal[1] + 1e-10 * principal[2]:
|
|
17
|
+
raise SimBridgeError("inertia must be positive definite and satisfy the triangle inequality")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def rotate_inertia(inertia, rotation):
|
|
21
|
+
rotation = np.asarray(rotation)
|
|
22
|
+
return rotation @ np.asarray(inertia) @ rotation.T
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def parallel_axis(mass, displacement):
|
|
26
|
+
d = np.asarray(displacement)
|
|
27
|
+
return mass * (np.dot(d, d) * np.eye(3) - np.outer(d, d))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def combine(parts):
|
|
31
|
+
"""Combine explicitly rigid parts (mass, COM, centroidal inertia), one frame."""
|
|
32
|
+
parts = list(parts)
|
|
33
|
+
for mass, _, inertia in parts:
|
|
34
|
+
validate_inertia(mass, inertia)
|
|
35
|
+
mass = sum(p[0] for p in parts)
|
|
36
|
+
if mass <= 0:
|
|
37
|
+
raise SimBridgeError("cannot combine an empty set of parts")
|
|
38
|
+
com = sum(m * np.asarray(c) for m, c, _ in parts) / mass
|
|
39
|
+
inertia = sum(np.asarray(i) + parallel_axis(m, np.asarray(c) - com) for m, c, i in parts)
|
|
40
|
+
validate_inertia(mass, inertia)
|
|
41
|
+
return mass, com, inertia
|
simbridge/errors.py
ADDED
|
File without changes
|