cmvr-es/model/update_joint_limits.py

315 lines
14 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Synchronize CSV angular limits into URDF, MJCF joints and position servos."""
from __future__ import annotations
import argparse
import csv
from dataclasses import dataclass, field
import math
import os
from pathlib import Path
import re
import stat
import sys
import tempfile
from xml.parsers import expat
MODELS_DIR = Path(__file__).resolve().parent
ATTRIBUTE = re.compile(rb'''([\w:.-]+)\s*=\s*(["'])(.*?)\2''', re.DOTALL)
@dataclass(frozen=True)
class Limits:
name: str
lower: float
upper: float
def read_limits(path: Path) -> list[Limits]:
"""Read a compact CSV or a SolidWorks URDF exporter CSV as radians."""
with path.open(encoding="utf-8-sig", newline="") as stream:
rows = csv.reader(stream, strict=True)
headers = [value.strip() for value in next(rows, [])]
if len(set(headers)) != len(headers):
raise ValueError("CSV contains duplicate column names")
solidworks = {"Joint Name", "Limit Lower", "Limit Upper"}.issubset(headers)
if solidworks:
name_key, lower_key, upper_key = "Joint Name", "Limit Lower", "Limit Upper"
else:
required = {"joint_name", "lower", "upper"}
if not required.issubset(headers) or set(headers) - required - {"unit"}:
raise ValueError("CSV headers must be joint_name,lower,upper,unit (unit is optional)")
name_key, lower_key, upper_key = "joint_name", "lower", "upper"
result = []
seen = set()
for values in rows:
if not values or not any(value.strip() for value in values):
continue
if len(values) != len(headers):
raise ValueError(f"CSV line {rows.line_num}: expected {len(headers)} columns")
row = dict(zip(headers, (value.strip() for value in values)))
name = row[name_key]
if solidworks and not name: # The root link has no incoming joint.
continue
if not name or name in seen:
raise ValueError(f"CSV line {rows.line_num}: empty or duplicate joint name {name!r}")
unit = "rad" if solidworks else row.get("unit", "rad")
if unit not in {"rad", "deg"}:
raise ValueError(f"CSV line {rows.line_num}: unit must be rad or deg")
try:
lower, upper = float(row[lower_key]), float(row[upper_key])
except ValueError as error:
raise ValueError(f"CSV line {rows.line_num}: invalid limits for {name}") from error
if not (math.isfinite(lower) and math.isfinite(upper) and lower < upper):
raise ValueError(f"CSV line {rows.line_num}: {name} needs finite lower < upper")
if unit == "deg":
lower, upper = math.radians(lower), math.radians(upper)
result.append(Limits(name, lower, upper))
seen.add(name)
if not result:
raise ValueError("CSV contains no joint limits")
return result
@dataclass
class Node:
tag: str
attrs: dict[str, str]
start: int
end: int
parents: tuple[str, ...]
children: list[Node] = field(default_factory=list)
class XmlFile:
"""Parse XML but edit only attribute bytes, preserving comments and newlines."""
def __init__(self, path: Path, expected_root: str):
self.path = path.resolve(strict=True)
self.before = self.path.read_bytes()
self.nodes: list[Node] = []
self.edits: list[tuple[int, int, bytes]] = []
stack: list[Node] = []
parser = expat.ParserCreate()
def start(tag: str, attrs: dict[str, str]) -> None:
begin = parser.CurrentByteIndex
end, quote = begin, None
while end < len(self.before):
char = self.before[end]
if quote is not None:
if char == quote:
quote = None
elif char in (34, 39):
quote = char
elif char == 62: # > outside a quoted attribute
break
end += 1
node = Node(tag, attrs, begin, end + 1, tuple(n.tag for n in stack))
if stack:
stack[-1].children.append(node)
stack.append(node)
self.nodes.append(node)
def reject_doctype(*_args: object) -> None:
raise ValueError(f"{self.path}: DTD/entity declarations are not supported")
parser.StartElementHandler = start
parser.EndElementHandler = lambda _tag: stack.pop()
parser.StartDoctypeDeclHandler = reject_doctype
parser.Parse(self.before, True)
if self.nodes[0].tag != expected_root:
raise ValueError(f"{self.path}: expected <{expected_root}> root")
def set_numbers(self, node: Node, attribute: str, values: tuple[float, ...]) -> bool:
if not all(math.isfinite(value) for value in values):
raise ValueError(f"{self.path}: non-finite {attribute} after unit conversion")
original = node.attrs.get(attribute)
if original is None:
raise ValueError(f"{self.path}: <{node.tag}> is missing {attribute}")
old = tuple(float(value) for value in original.split())
if len(old) != len(values) or not all(math.isfinite(value) for value in old):
raise ValueError(f"{self.path}: invalid {attribute}={original!r}")
if all(math.isclose(a, b, rel_tol=1e-14, abs_tol=1e-15) for a, b in zip(old, values)):
return False
for match in ATTRIBUTE.finditer(self.before[node.start:node.end]):
if match[1].decode("utf-8") == attribute:
value = " ".join(format(number if number else 0.0, ".15g") for number in values)
self.edits.append((node.start + match.start(3), node.start + match.end(3), value.encode()))
return True
raise ValueError(f"{self.path}: cannot locate attribute {attribute}")
def after(self) -> bytes:
content = self.before
for start, end, value in sorted(self.edits, reverse=True):
content = content[:start] + value + content[end:]
return content
def one(nodes: list[Node], description: str) -> Node:
if len(nodes) != 1:
raise ValueError(f"{description}: expected one match, found {len(nodes)}")
return nodes[0]
def prepare(limits: list[Limits], urdf: XmlFile, mjcf: XmlFile, actuators: XmlFile) -> list[str]:
if len({document.path for document in (urdf, mjcf, actuators)}) != 3:
raise ValueError("URDF, MJCF and actuator paths must be three separate files")
compilers = [node for node in mjcf.nodes if node.tag == "compiler" and node.parents == ("mujoco",)]
angle = "degree"
for compiler in compilers:
angle = compiler.attrs.get("angle", angle)
if angle not in {"radian", "degree"}:
raise ValueError(f"Unsupported MJCF compiler angle: {angle}")
# This script does not resolve a complete MJCF default/include hierarchy.
# Reject disabled-limit defaults conservatively, including unused classes,
# rather than reporting success with a range that MuJoCo will not enforce.
for document in (mjcf, actuators):
for node in document.nodes:
if "default" in node.parents:
for flag in ("limited", "ctrllimited"):
if node.attrs.get(flag) == "false":
raise ValueError(f"{document.path}: default {flag}=false is not supported")
# Scalar position servos in this workflow use gear=1, so ctrl is radians.
# Reject non-unit gears even in defaults rather than silently writing wrong ranges.
for node in actuators.nodes:
if "gear" in node.attrs:
gear = node.attrs["gear"].split()
if not gear or float(gear[0]) != 1.0:
raise ValueError("Only gear=1 position actuators are supported")
report = []
for limit in limits:
joint = one([n for n in urdf.nodes if n.tag == "joint" and n.parents == ("robot",)
and n.attrs.get("name") == limit.name], f"URDF joint {limit.name}")
if joint.attrs.get("type") != "revolute":
raise ValueError(f"{limit.name}: only revolute URDF joints are supported")
urdf_limit = one([n for n in joint.children if n.tag == "limit"], f"{limit.name} URDF limit")
mj_joint = one([n for n in mjcf.nodes if n.tag == "joint" and "worldbody" in n.parents
and n.attrs.get("name") == limit.name], f"MJCF joint {limit.name}")
if mj_joint.attrs.get("type", "hinge") != "hinge":
raise ValueError(f"{limit.name}: only hinge MJCF joints are supported")
if mj_joint.attrs.get("limited") == "false":
raise ValueError(f"{limit.name}: MJCF joint has limited=false")
servo = one([n for n in actuators.nodes if n.tag == "position" and n.parents[-1:] == ("actuator",)
and n.attrs.get("joint") == limit.name], f"Position actuator for {limit.name}")
if servo.attrs.get("ctrllimited") == "false":
raise ValueError(f"{limit.name}: actuator has ctrllimited=false")
radians = (limit.lower, limit.upper)
mj_range = tuple(math.degrees(value) for value in radians) if angle == "degree" else radians
changed = []
lower_changed = urdf.set_numbers(urdf_limit, "lower", (limit.lower,))
upper_changed = urdf.set_numbers(urdf_limit, "upper", (limit.upper,))
if lower_changed or upper_changed:
changed.append(f"URDF [{urdf_limit.attrs['lower']}, {urdf_limit.attrs['upper']}]")
if mjcf.set_numbers(mj_joint, "range", mj_range):
changed.append(f"MJCF [{mj_joint.attrs['range']}] ({angle})")
if actuators.set_numbers(servo, "ctrlrange", radians):
changed.append(f"actuator [{servo.attrs['ctrlrange']}]")
if changed:
report.append(f"{limit.name}: {', '.join(changed)} -> [{limit.lower:.15g}, {limit.upper:.15g}] rad")
return report
def stage(path: Path, content: bytes, mode: int) -> Path:
"""Stage next to the destination so replacement is atomic on its filesystem."""
fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
temporary = Path(name)
try:
with os.fdopen(fd, "wb") as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
temporary.chmod(mode)
return temporary
except BaseException:
temporary.unlink(missing_ok=True)
raise
def write_files(documents: list[XmlFile]) -> None:
"""Validate everything first; roll back completed replacements on write failure."""
pending = []
committed = []
retained_backups: set[Path] = set()
try:
for document in documents:
if not document.edits:
continue
if document.path.read_bytes() != document.before:
raise ValueError(f"File changed while preparing update: {document.path}")
mode = stat.S_IMODE(document.path.stat().st_mode)
new = stage(document.path, document.after(), mode)
pending.append((document, new, None))
backup = stage(document.path, document.before, mode)
pending[-1] = (document, new, backup)
for document, new, backup in pending:
if document.path.read_bytes() != document.before:
raise ValueError(f"File changed while preparing update: {document.path}")
os.replace(new, document.path)
committed.append((document, backup))
except BaseException as error:
for document, backup in reversed(committed):
try:
os.replace(backup, document.path)
except OSError:
retained_backups.add(backup)
if retained_backups:
locations = ", ".join(str(path) for path in sorted(retained_backups))
raise OSError(f"Update failed ({error}); rollback incomplete. Original backups retained: {locations}") from error
raise
finally:
for _document, new, backup in pending:
new.unlink(missing_ok=True)
if backup is not None and backup not in retained_backups:
backup.unlink(missing_ok=True)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=__doc__, allow_abbrev=False,
epilog="Example: python3 model/update_joint_limits.py --xiaozhao --dry-run",
)
selectors = parser.add_mutually_exclusive_group(required=True)
reserved = {"help", "csv", "urdf", "mjcf", "xml", "actuators", "dry-run"}
for folder in sorted(MODELS_DIR.iterdir()):
if (folder.is_dir() and not folder.name.startswith((".", "__"))
and folder.name not in reserved):
selectors.add_argument(
f"--{folder.name}", dest="model_name", action="store_const", const=folder.name,
help=f"read {folder.name}/config/joint_limits.csv and update this model",
)
parser.add_argument("--csv", type=Path, help="override <model>/config/joint_limits.csv")
parser.add_argument("--urdf", type=Path, help="override <model>/urdf/<model>.urdf")
parser.add_argument("--mjcf", "--xml", type=Path, help="override <model>/xml/<model>.xml (not scene.xml)")
parser.add_argument("--actuators", type=Path, help="override <model>/xml/actuators.xml")
parser.add_argument("--dry-run", action="store_true", help="show changes without writing any files")
args = parser.parse_args(argv)
model_dir = MODELS_DIR / args.model_name
try:
limits = read_limits(args.csv or model_dir / "config/joint_limits.csv")
documents = [
XmlFile(args.urdf or model_dir / f"urdf/{args.model_name}.urdf", "robot"),
XmlFile(args.mjcf or model_dir / f"xml/{args.model_name}.xml", "mujoco"),
XmlFile(args.actuators or model_dir / "xml/actuators.xml", "mujoco"),
]
report = prepare(limits, *documents)
for line in report:
print(line)
if args.dry_run:
print(f"Dry run: {len(limits)} joints checked, {len(report)} changed; no files written.")
elif report:
write_files(documents)
print(f"Updated {len(report)} joints in {sum(bool(doc.edits) for doc in documents)} files.")
else:
print(f"No changes needed ({len(limits)} joints checked).")
return 0
except (ValueError, OSError, UnicodeError, csv.Error, expat.ExpatError) as error:
print(f"Error: {error}", file=sys.stderr)
return 2
if __name__ == "__main__":
raise SystemExit(main())