Add the pedestal-free xiaozhao URDF, mesh assets, and separate MuJoCo robot, environment, and position-actuator XML files. Align joint frames, rotation directions, inertial transforms, and limits with the calibrated URDF, including the mirrored right hand, and retain the original SolidWorks URDF export. Add a model-selectable CSV limit updater with unit conversion, validation, dry-run support, and rollback on write failures. Synchronize the calibration CSV, document the workflow, add regression tests, and ignore export logs. Validation: 14 joint-limit tests passed; all joint and actuator ranges agree with the URDF. Kinematics and inertial checks passed, along with a 3000-step MuJoCo 3.3.7 simulation and desktop scene loading.
407 lines
17 KiB
Python
407 lines
17 KiB
Python
"""End-to-end tests for synchronizing CSV joint limits across model files."""
|
|
|
|
from pathlib import Path
|
|
import math
|
|
import re
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest import mock
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
SCRIPT = Path(__file__).resolve().parents[2] / "model" / "update_joint_limits.py"
|
|
|
|
URDF = b'''<?xml version="1.0"?>
|
|
<robot name="fixture">
|
|
<!-- Keep the source comment and formatting. -->
|
|
<link name="base"/>
|
|
<link name="arm"/>
|
|
<link name="wrist"/>
|
|
<joint name="shoulder" type="revolute">
|
|
<parent link="base"/><child link="arm"/><axis xyz="0 0 1"/>
|
|
<limit lower="-1" upper="1" effort="30" velocity="2"/>
|
|
</joint>
|
|
<joint name="wrist" type="revolute">
|
|
<parent link="arm"/><child link="wrist"/><axis xyz="0 1 0"/>
|
|
<limit lower="-0.5" upper="0.5" effort="10" velocity="3"/>
|
|
</joint>
|
|
</robot>
|
|
'''
|
|
|
|
MJCF = b'''<mujoco model="fixture">
|
|
<compiler angle="radian"/>
|
|
<!-- Joint limits are independent of visual materials. -->
|
|
<worldbody>
|
|
<body name="arm">
|
|
<joint name="shoulder" type="hinge" range="-1 1" axis="0 0 1"/>
|
|
<body name="wrist">
|
|
<joint name="wrist" type="hinge" range="-0.5 0.5" axis="0 1 0"/>
|
|
</body>
|
|
</body>
|
|
</worldbody>
|
|
</mujoco>
|
|
'''
|
|
|
|
ACTUATORS = b'''<mujoco model="fixture_actuators">
|
|
<default><default class="position_servo"><position kp="100"/></default></default>
|
|
<!-- Names intentionally differ from the joints and list order is reversed. -->
|
|
<actuator>
|
|
<position name="small_motor" class="position_servo" joint="wrist"
|
|
ctrlrange="-0.5 0.5" kp="20"/>
|
|
<position name="large_motor" class="position_servo" joint="shoulder"
|
|
ctrlrange="-1 1" kp="100"/>
|
|
</actuator>
|
|
</mujoco>
|
|
'''
|
|
|
|
|
|
class UpdateJointLimitsTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temporary = tempfile.TemporaryDirectory(prefix="joint-limit-test-")
|
|
self.addCleanup(self.temporary.cleanup)
|
|
self.directory = Path(self.temporary.name)
|
|
self.csv = self.directory / "limits.csv"
|
|
self.urdf = self.directory / "robot.urdf"
|
|
self.mjcf = self.directory / "robot.xml"
|
|
self.actuators = self.directory / "actuators.xml"
|
|
self.targets = (self.urdf, self.mjcf, self.actuators)
|
|
self.urdf.write_bytes(URDF)
|
|
self.mjcf.write_bytes(MJCF)
|
|
self.actuators.write_bytes(ACTUATORS)
|
|
|
|
def run_cli(self, csv_text, *options, encoding="utf-8"):
|
|
self.csv.write_bytes(csv_text.encode(encoding))
|
|
return subprocess.run(
|
|
[
|
|
sys.executable, str(SCRIPT), "--xiaozhao",
|
|
"--csv", str(self.csv), "--urdf", str(self.urdf),
|
|
"--mjcf", str(self.mjcf), "--actuators", str(self.actuators),
|
|
*options,
|
|
],
|
|
# Explicit paths must work outside the repository working directory.
|
|
cwd=self.directory,
|
|
text=True,
|
|
capture_output=True,
|
|
check=False,
|
|
)
|
|
|
|
def snapshot(self):
|
|
return {path: path.read_bytes() for path in self.targets}
|
|
|
|
def copied_script_with_models(self):
|
|
model_root = self.directory / "model"
|
|
model_root.mkdir()
|
|
copied_script = model_root / "update_joint_limits.py"
|
|
copied_script.write_bytes(SCRIPT.read_bytes())
|
|
for name in ("demobot", "otherbot"):
|
|
model = model_root / name
|
|
for subdirectory in ("config", "urdf", "xml"):
|
|
(model / subdirectory).mkdir(parents=True)
|
|
(model / "config" / "joint_limits.csv").write_text(
|
|
"joint_name,lower,upper,unit\nshoulder,-45,90,deg\n",
|
|
encoding="utf-8",
|
|
)
|
|
(model / "urdf" / f"{name}.urdf").write_bytes(URDF)
|
|
(model / "xml" / f"{name}.xml").write_bytes(MJCF)
|
|
(model / "xml" / "actuators.xml").write_bytes(ACTUATORS)
|
|
working_directory = self.directory / "unrelated-working-directory"
|
|
working_directory.mkdir()
|
|
return copied_script, model_root, working_directory
|
|
|
|
def assert_success(self, result):
|
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
|
|
|
def assert_joint_limits(self, joint_name, lower, upper):
|
|
urdf = ET.parse(self.urdf).getroot()
|
|
mjcf = ET.parse(self.mjcf).getroot()
|
|
actuators = ET.parse(self.actuators).getroot()
|
|
limit = urdf.find(f"joint[@name='{joint_name}']/limit")
|
|
joint = mjcf.find(f".//worldbody//joint[@name='{joint_name}']")
|
|
actuator = actuators.find(f"actuator/position[@joint='{joint_name}']")
|
|
actual_ranges = (
|
|
(float(limit.get("lower")), float(limit.get("upper"))),
|
|
tuple(map(float, joint.get("range").split())),
|
|
tuple(map(float, actuator.get("ctrlrange").split())),
|
|
)
|
|
for actual in actual_ranges:
|
|
self.assertAlmostEqual(actual[0], lower, places=10)
|
|
self.assertAlmostEqual(actual[1], upper, places=10)
|
|
|
|
def test_mixed_units_update_all_targets_and_preserve_other_content(self):
|
|
before = self.snapshot()
|
|
result = self.run_cli(
|
|
"joint_name,lower,upper,unit\n"
|
|
"shoulder,-90,45,deg\n"
|
|
"wrist,-0.2,0.3,rad\n"
|
|
)
|
|
self.assert_success(result)
|
|
self.assert_joint_limits("shoulder", -math.pi / 2, math.pi / 4)
|
|
self.assert_joint_limits("wrist", -0.2, 0.3)
|
|
# Permit numeric formatting changes only inside the intended attributes.
|
|
pattern = rb'\b(lower|upper|range|ctrlrange)="[^"]*"'
|
|
for path, original in before.items():
|
|
self.assertEqual(
|
|
re.sub(pattern, rb'\1="LIMIT"', path.read_bytes()),
|
|
re.sub(pattern, rb'\1="LIMIT"', original),
|
|
)
|
|
|
|
def test_model_selector_resolves_defaults_relative_to_copied_script(self):
|
|
copied_script, model_root, cwd = self.copied_script_with_models()
|
|
other_model = model_root / "otherbot"
|
|
untouched = {
|
|
path: path.read_bytes() for path in other_model.rglob("*") if path.is_file()
|
|
}
|
|
result = subprocess.run(
|
|
[sys.executable, str(copied_script), "--demobot"],
|
|
cwd=cwd,
|
|
text=True,
|
|
capture_output=True,
|
|
check=False,
|
|
)
|
|
self.assert_success(result)
|
|
self.urdf = model_root / "demobot" / "urdf" / "demobot.urdf"
|
|
self.mjcf = model_root / "demobot" / "xml" / "demobot.xml"
|
|
self.actuators = model_root / "demobot" / "xml" / "actuators.xml"
|
|
self.assert_joint_limits("shoulder", -math.pi / 4, math.pi / 2)
|
|
self.assert_joint_limits("wrist", -0.5, 0.5)
|
|
for path, contents in untouched.items():
|
|
self.assertEqual(path.read_bytes(), contents)
|
|
|
|
def test_missing_unknown_or_multiple_model_selectors_never_write(self):
|
|
copied_script, model_root, cwd = self.copied_script_with_models()
|
|
before = {
|
|
path: path.read_bytes() for path in model_root.rglob("*") if path.is_file()
|
|
}
|
|
selections = (
|
|
(),
|
|
("--ghostbot",),
|
|
("--demobot", "--otherbot"),
|
|
("--demobot", "--ghostbot"),
|
|
)
|
|
for selection in selections:
|
|
with self.subTest(selection=selection):
|
|
result = subprocess.run(
|
|
[sys.executable, str(copied_script), *selection],
|
|
cwd=cwd,
|
|
text=True,
|
|
capture_output=True,
|
|
check=False,
|
|
)
|
|
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
|
self.assertTrue(result.stderr.strip())
|
|
after = {
|
|
path: path.read_bytes()
|
|
for path in model_root.rglob("*") if path.is_file()
|
|
}
|
|
self.assertEqual(after, before)
|
|
|
|
def test_partial_csv_leaves_unlisted_joint_unchanged(self):
|
|
result = self.run_cli("joint_name,lower,upper,unit\nwrist,-20,35,deg\n")
|
|
self.assert_success(result)
|
|
self.assert_joint_limits("shoulder", -1, 1)
|
|
self.assert_joint_limits("wrist", math.radians(-20), math.radians(35))
|
|
|
|
def test_solidworks_csv_with_bom_skips_root_link(self):
|
|
result = self.run_cli(
|
|
"Link Name,Joint Name,Joint Type,Limit Lower,Limit Upper,Limit Effort\n"
|
|
"base,,,,,\n"
|
|
"arm,shoulder,revolute,-0.7,0.8,30\n",
|
|
encoding="utf-8-sig",
|
|
)
|
|
self.assert_success(result)
|
|
self.assert_joint_limits("shoulder", -0.7, 0.8)
|
|
self.assert_joint_limits("wrist", -0.5, 0.5)
|
|
|
|
def test_degree_mjcf_range_keeps_urdf_and_actuator_in_radians(self):
|
|
self.mjcf.write_bytes(MJCF.replace(b'angle="radian"', b'angle="degree"'))
|
|
result = self.run_cli("joint_name,lower,upper,unit\nshoulder,-45,90,deg\n")
|
|
self.assert_success(result)
|
|
joint = ET.parse(self.mjcf).find(".//worldbody//joint[@name='shoulder']")
|
|
self.assertEqual(tuple(map(float, joint.get("range").split())), (-45, 90))
|
|
limit = ET.parse(self.urdf).find("joint[@name='shoulder']/limit")
|
|
actuator = ET.parse(self.actuators).find("actuator/position[@joint='shoulder']")
|
|
self.assertAlmostEqual(float(limit.get("lower")), -math.pi / 4, places=10)
|
|
self.assertAlmostEqual(float(limit.get("upper")), math.pi / 2, places=10)
|
|
actual = tuple(map(float, actuator.get("ctrlrange").split()))
|
|
self.assertAlmostEqual(actual[0], -math.pi / 4, places=10)
|
|
self.assertAlmostEqual(actual[1], math.pi / 2, places=10)
|
|
|
|
def test_dry_run_and_repeated_application(self):
|
|
csv_text = "joint_name,lower,upper,unit\nshoulder,-30,60,deg\n"
|
|
before = self.snapshot()
|
|
self.assert_success(self.run_cli(csv_text, "--dry-run"))
|
|
self.assertEqual(self.snapshot(), before)
|
|
self.assert_success(self.run_cli(csv_text))
|
|
applied = self.snapshot()
|
|
self.assertNotEqual(applied, before)
|
|
self.assert_success(self.run_cli(csv_text))
|
|
self.assertEqual(self.snapshot(), applied)
|
|
|
|
def test_invalid_rows_never_partially_write(self):
|
|
prefix = "joint_name,lower,upper,unit\nshoulder,-0.8,0.8,rad\n"
|
|
invalid_rows = (
|
|
"typo,-0.1,0.1,rad\n",
|
|
"shoulder,-0.2,0.2,rad\n",
|
|
"wrist,0.3,-0.3,rad\n",
|
|
"wrist,0.3,0.3,rad\n",
|
|
"wrist,nan,0.3,rad\n",
|
|
"wrist,-0.3,inf,rad\n",
|
|
"wrist,-0.3,0.3,turns\n",
|
|
"wrist,,0.3,rad\n",
|
|
",-0.3,0.3,rad\n",
|
|
)
|
|
for row in invalid_rows:
|
|
with self.subTest(row=row):
|
|
before = self.snapshot()
|
|
result = self.run_cli(prefix + row)
|
|
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
|
self.assertTrue(result.stderr.strip())
|
|
self.assertEqual(self.snapshot(), before)
|
|
|
|
def test_missing_joint_in_target_prevents_all_writes(self):
|
|
cases = (
|
|
(self.mjcf, b'name="wrist" type="hinge"', b'name="renamed" type="hinge"'),
|
|
(self.actuators, b'joint="wrist"', b'joint="renamed"'),
|
|
)
|
|
for path, old, new in cases:
|
|
with self.subTest(path=path.name):
|
|
original = path.read_bytes()
|
|
path.write_bytes(original.replace(old, new))
|
|
before = self.snapshot()
|
|
result = self.run_cli(
|
|
"joint_name,lower,upper,unit\n"
|
|
"shoulder,-0.8,0.8,rad\nwrist,-0.3,0.3,rad\n"
|
|
)
|
|
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
|
self.assertEqual(self.snapshot(), before)
|
|
path.write_bytes(original)
|
|
|
|
def test_missing_file_prevents_writing_other_files(self):
|
|
self.mjcf.unlink()
|
|
before = {path: path.read_bytes() for path in (self.urdf, self.actuators)}
|
|
result = self.run_cli("joint_name,lower,upper,unit\nshoulder,-0.8,0.8,rad\n")
|
|
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
|
for path, contents in before.items():
|
|
self.assertEqual(path.read_bytes(), contents)
|
|
self.assertFalse(self.mjcf.exists())
|
|
|
|
def test_disabled_limit_defaults_and_nonunit_gear_prevent_all_writes(self):
|
|
cases = (
|
|
(
|
|
"inherited actuator control limits disabled",
|
|
self.actuators,
|
|
ACTUATORS.replace(b'<position kp="100"/>', b'<position kp="100" ctrllimited="false"/>'),
|
|
),
|
|
(
|
|
"inherited joint limits disabled",
|
|
self.mjcf,
|
|
MJCF.replace(b" <worldbody>", b' <default><joint limited="false"/></default>\n <worldbody>'),
|
|
),
|
|
(
|
|
"unused class rejected conservatively",
|
|
self.mjcf,
|
|
MJCF.replace(
|
|
b" <worldbody>",
|
|
b' <default><default class="unused"><joint limited="false"/></default></default>\n <worldbody>',
|
|
),
|
|
),
|
|
(
|
|
"inherited non-unit transmission gear",
|
|
self.actuators,
|
|
ACTUATORS.replace(b'<position kp="100"/>', b'<position kp="100" gear="2"/>'),
|
|
),
|
|
)
|
|
for description, path, contents in cases:
|
|
with self.subTest(description=description):
|
|
original = path.read_bytes()
|
|
try:
|
|
path.write_bytes(contents)
|
|
before = self.snapshot()
|
|
result = self.run_cli(
|
|
"joint_name,lower,upper,unit\n"
|
|
"shoulder,-0.8,0.8,rad\nwrist,-0.3,0.3,rad\n"
|
|
)
|
|
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
|
self.assertTrue(result.stderr.strip())
|
|
self.assertEqual(self.snapshot(), before)
|
|
finally:
|
|
path.write_bytes(original)
|
|
|
|
def prepared_update(self):
|
|
with mock.patch.object(sys, "path", [str(SCRIPT.parent), *sys.path]):
|
|
import update_joint_limits
|
|
documents = [
|
|
update_joint_limits.XmlFile(self.urdf, "robot"),
|
|
update_joint_limits.XmlFile(self.mjcf, "mujoco"),
|
|
update_joint_limits.XmlFile(self.actuators, "mujoco"),
|
|
]
|
|
update_joint_limits.prepare(
|
|
[update_joint_limits.Limits("shoulder", -0.8, 0.8)], *documents
|
|
)
|
|
return update_joint_limits, documents
|
|
|
|
def test_second_file_replace_failure_rolls_back_and_removes_temporary_files(self):
|
|
updater, documents = self.prepared_update()
|
|
before = self.snapshot()
|
|
real_replace = updater.os.replace
|
|
calls = 0
|
|
|
|
def replace_with_commit_failure(source, destination):
|
|
nonlocal calls
|
|
calls += 1
|
|
if calls == 2:
|
|
raise OSError("simulated second commit failure")
|
|
return real_replace(source, destination)
|
|
|
|
with mock.patch.object(updater.os, "replace", side_effect=replace_with_commit_failure):
|
|
with self.assertRaisesRegex(OSError, "second commit failure"):
|
|
updater.write_files(documents)
|
|
|
|
self.assertEqual(calls, 3) # First commit, failed second commit, rollback.
|
|
self.assertEqual(self.snapshot(), before)
|
|
self.assertEqual(list(self.directory.glob(".*.tmp")), [])
|
|
|
|
def test_failed_rollback_retains_original_backup_for_recovery(self):
|
|
updater, documents = self.prepared_update()
|
|
before = self.snapshot()
|
|
real_replace = updater.os.replace
|
|
calls = 0
|
|
|
|
def replace_with_commit_and_rollback_failure(source, destination):
|
|
nonlocal calls
|
|
calls += 1
|
|
if calls in (2, 3):
|
|
raise OSError("simulated replacement failure")
|
|
return real_replace(source, destination)
|
|
|
|
with mock.patch.object(updater.os, "replace", side_effect=replace_with_commit_and_rollback_failure):
|
|
with self.assertRaisesRegex(OSError, "Original backups retained") as raised:
|
|
updater.write_files(documents)
|
|
|
|
self.assertEqual(calls, 3)
|
|
backups = list(self.directory.glob(".*.tmp"))
|
|
self.assertEqual(len(backups), 1)
|
|
self.assertEqual(backups[0].read_bytes(), before[self.urdf])
|
|
self.assertIn(str(backups[0]), str(raised.exception))
|
|
self.assertEqual(self.urdf.read_bytes(), documents[0].after())
|
|
self.assertEqual(self.mjcf.read_bytes(), before[self.mjcf])
|
|
self.assertEqual(self.actuators.read_bytes(), before[self.actuators])
|
|
|
|
def test_read_only_crlf_urdf_preserves_permissions_and_line_endings(self):
|
|
self.urdf.write_bytes(URDF.replace(b"\n", b"\r\n"))
|
|
self.urdf.chmod(0o444)
|
|
result = self.run_cli("joint_name,lower,upper,unit\nshoulder,-0.6,0.6,rad\n")
|
|
self.assert_success(result)
|
|
self.assert_joint_limits("shoulder", -0.6, 0.6)
|
|
self.assertEqual(stat.S_IMODE(self.urdf.stat().st_mode), 0o444)
|
|
updated = self.urdf.read_bytes()
|
|
self.assertNotIn(b"\n", updated.replace(b"\r\n", b""))
|
|
self.assertIn(b"<!-- Keep the source comment and formatting. -->", updated)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|