Skip to content

Commit 78fd485

Browse files
authored
move to safeloader for yaml load (#723)
1 parent 8e734f3 commit 78fd485

8 files changed

Lines changed: 196 additions & 19 deletions

File tree

‎curobo/_src/robot/builder/builder_robot.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@
2323
from curobo._src.robot.kinematics.kinematics import Kinematics
2424
from curobo._src.robot.kinematics.kinematics_cfg import KinematicsCfg
2525
from curobo._src.state.state_joint import JointState
26-
from curobo._src.robot.loader.kinematics_loader_cfg import KinematicsLoaderCfg
26+
from curobo._src.robot.loader.kinematics_loader_cfg import (
27+
KinematicsLoaderCfg,
28+
serialize_kinematics_config,
29+
)
2730
from curobo._src.robot.parser.parser_urdf import UrdfRobotParser
2831
from curobo._src.types.content_path import ContentPath
2932
from curobo._src.types.device_cfg import DeviceCfg
@@ -668,6 +671,7 @@ def save(
668671
output_path_obj.parent.mkdir(parents=True, exist_ok=True)
669672

670673
# Write YAML
674+
data_dict["kinematics"] = serialize_kinematics_config(data_dict["kinematics"])
671675
write_yaml(data_dict, str(output_path))
672676
log_info(f"Saved robot configuration to: {output_path}")
673677

@@ -733,6 +737,7 @@ def save_xrdf(
733737
del config_dict["kinematics"]["device_cfg"]
734738

735739
# Convert to XRDF format using utility function
740+
config_dict["kinematics"] = serialize_kinematics_config(config_dict["kinematics"])
736741
xrdf_dict = convert_curobo_to_xrdf(
737742
config_dict,
738743
geometry_name=geometry_name,

‎curobo/_src/robot/loader/kinematics_loader_cfg.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,51 @@
1616
from dataclasses import dataclass
1717
from typing import Any, Dict, List, Optional, Union
1818

19+
import numpy as np
20+
import torch
21+
1922
from curobo._src.robot.types.cspace_params import CSpaceParams
2023
from curobo._src.robot.types.link_params import LinkParams
2124
from curobo._src.types.device_cfg import DeviceCfg
25+
from curobo._src.types.pose import Pose
2226
from curobo._src.util.logging import log_and_raise, log_warn
2327
from curobo._src.util_file import get_assets_path, get_robot_configs_path, join_path, load_yaml
2428

2529

30+
def serialize_kinematics_config(data: Dict[str, Any]) -> Dict[str, Any]:
31+
"""Convert loader fields to YAML data, omitting runtime options without mutating inputs."""
32+
33+
def to_yaml_value(value: Any) -> Any:
34+
"""Convert numeric values and known robot parameter types to plain YAML data."""
35+
if isinstance(value, torch.Tensor):
36+
return value.detach().cpu().tolist()
37+
if isinstance(value, (np.ndarray, np.generic)):
38+
return value.tolist()
39+
if isinstance(value, CSpaceParams):
40+
value = {k: v for k, v in vars(value).items() if k != "device_cfg"}
41+
elif isinstance(value, LinkParams):
42+
link = vars(value).copy()
43+
transform = torch.eye(4, device="cpu", dtype=torch.float32)
44+
transform[:3] = torch.as_tensor(value.fixed_transform, device="cpu", dtype=torch.float32)
45+
link["fixed_transform"] = Pose.from_matrix(transform).tolist()
46+
link["joint_type"] = value.joint_type.name
47+
value = link
48+
if isinstance(value, dict):
49+
return {k: to_yaml_value(v) for k, v in value.items()}
50+
if isinstance(value, (list, tuple)):
51+
return [to_yaml_value(v) for v in value]
52+
return value
53+
54+
data = {
55+
k: v for k, v in data.items()
56+
if k not in ("device_cfg", "load_collision_spheres", "num_envs")
57+
}
58+
# A supplied cspace dictionary can already contain its device configuration.
59+
if isinstance(data.get("cspace"), dict):
60+
data["cspace"] = {k: v for k, v in data["cspace"].items() if k != "device_cfg"}
61+
return to_yaml_value(data)
62+
63+
2664
@dataclass
2765
class KinematicsLoaderCfg:
2866
"""Robot representation generator configuration, loads from a dictionary."""
@@ -197,4 +235,3 @@ def __post_init__(self):
197235

198236
if self.grasp_contact_link_names is not None:
199237
self.grasp_contact_link_names = copy.deepcopy(self.grasp_contact_link_names)
200-

‎curobo/_src/types/robot.py‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,13 @@
1212
from curobo._src.robot.kinematics.kinematics_cfg import KinematicsCfg
1313

1414
# CuRobo
15-
from curobo._src.robot.loader.kinematics_loader_cfg import KinematicsLoaderCfg
15+
from curobo._src.robot.loader.kinematics_loader_cfg import (
16+
KinematicsLoaderCfg,
17+
serialize_kinematics_config,
18+
)
1619
from curobo._src.robot.types.cspace_params import CSpaceParams
1720
from curobo._src.types.device_cfg import DeviceCfg
21+
from curobo._src.util.logging import log_and_raise
1822
from curobo._src.util_file import write_yaml
1923

2024

@@ -138,16 +142,14 @@ def from_basic(
138142
device_cfg=device_cfg,
139143
)
140144

141-
def write_config(self, file_path):
142-
dictionary = vars(self)
143-
dictionary["kinematics"] = vars(dictionary["kinematics"])
144-
# Handle dynamics config - just store a flag
145-
if dictionary["dynamics"] is not None:
146-
dictionary["load_dynamics"] = True
147-
dictionary.pop("dynamics") # Don't serialize the full config
148-
else:
149-
dictionary["load_dynamics"] = False
150-
dictionary.pop("dynamics", None)
145+
def write_config(self, file_path: str) -> None:
146+
"""Write a reloadable robot YAML configuration without serializing runtime objects."""
147+
if self.kinematics.generator_config is None:
148+
log_and_raise("Writing a robot configuration requires its generator_config.")
149+
dictionary = {
150+
"kinematics": serialize_kinematics_config(vars(self.kinematics.generator_config)),
151+
"load_dynamics": self.dynamics is not None,
152+
}
151153
write_yaml(dictionary, file_path)
152154

153155
@property

‎curobo/_src/util/config_io.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
# Third Party
1616
import yaml
17-
from yaml import CLoader as Loader
17+
from yaml import SafeLoader as Loader
1818

1919
# CuRobo
2020

@@ -100,15 +100,16 @@ def load_yaml(file_path: Union[str, Dict]) -> Dict:
100100
return resolve_config(file_path)
101101

102102

103-
def write_yaml(data: Dict, file_path: str):
103+
def write_yaml(data: Dict, file_path: str) -> None:
104104
"""Write dictionary to yaml file.
105105
106106
Args:
107107
data: Dictionary to write to yaml file.
108108
file_path: Path to write the yaml file.
109109
"""
110+
yaml_text = yaml.safe_dump(data)
110111
with open(file_path, "w") as file:
111-
yaml.dump(data, file)
112+
file.write(yaml_text)
112113

113114

114115
def copy_file_to_path(source_file: str, destination_path: str) -> str:

‎curobo/tests/_src/robot/builder/test_builder_robot.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,83 @@
88
from pathlib import Path
99

1010
# Third Party
11+
import numpy as np
1112
import pytest
13+
import yaml
1214

1315
from curobo._src.geom.sphere_fit.types import SphereFitType
1416

1517
# CuRobo
1618
from curobo._src.robot.builder.builder_robot import RobotBuilder
19+
from curobo._src.robot.loader.kinematics_loader_cfg import KinematicsLoaderCfg
20+
from curobo._src.robot.types.joint_types import JointType
21+
from curobo._src.robot.types.link_params import LinkParams
1722
from curobo._src.types.device_cfg import DeviceCfg
1823
from curobo._src.util_file import get_assets_path, get_robot_configs_path, join_path, load_yaml
1924

2025
FAST_ITERATIONS = 50
2126

2227

28+
@pytest.mark.parametrize("output_format", ["yaml", "yaml_without_cspace_generation", "xrdf"])
29+
def test_safe_export(
30+
tmp_path: Path,
31+
cpu_device_cfg: DeviceCfg,
32+
monkeypatch: pytest.MonkeyPatch,
33+
output_format: str,
34+
) -> None:
35+
"""Export typed cspace and extra links as portable data without changing the source."""
36+
data = load_yaml(join_path(get_robot_configs_path(), "simple_mimic_robot.yml"))
37+
config = KinematicsLoaderCfg(**data["robot_cfg"]["kinematics"], device_cfg=cpu_device_cfg)
38+
link = LinkParams(
39+
link_name="sensor",
40+
parent_link_name="ee_link",
41+
joint_name="sensor_joint",
42+
joint_type=JointType.FIXED,
43+
fixed_transform=np.array(
44+
[[0, -1, 0, 1], [1, 0, 0, 2], [0, 0, 1, 3]], dtype=np.float32
45+
),
46+
link_com=np.zeros(3, dtype=np.float32),
47+
link_inertia=np.zeros(6, dtype=np.float32),
48+
)
49+
config.extra_links = {"sensor": link}
50+
config.collision_spheres = {
51+
"ee_link": [{"center": np.zeros(3, dtype=np.float32), "radius": np.float32(0.1)}]
52+
}
53+
# Isolate export from mesh loading and collision fitting in the constructor.
54+
builder = RobotBuilder.__new__(RobotBuilder)
55+
# Exercise a cspace dictionary that already carries device and tensor fields.
56+
builder._cspace_config = vars(config.cspace).copy()
57+
output_path = tmp_path / "robot.yaml"
58+
if output_format == "xrdf":
59+
builder.save_xrdf(config, str(output_path))
60+
else:
61+
builder.save(config, str(output_path), include_cspace=output_format == "yaml")
62+
output = yaml.safe_load(output_path.read_text())
63+
assert "!!python" not in output_path.read_text()
64+
if output_format == "xrdf":
65+
assert output["cspace"]["joint_names"] == ["active_joint_2"]
66+
frame = output["modifiers"][-1]["add_frame"]
67+
assert frame["joint_type"] == "FIXED"
68+
assert frame["fixed_transform"]["position"] == [1.0, 2.0, 3.0]
69+
else:
70+
saved = output["kinematics"]
71+
assert "device_cfg" not in saved
72+
assert "device_cfg" not in saved["cspace"]
73+
assert saved["cspace"]["default_joint_position"] == pytest.approx([0.3, 0.0])
74+
# LinkParams.create currently defaults to CUDA; keep this I/O test on CPU.
75+
monkeypatch.setattr(
76+
"curobo._src.robot.types.link_params.DeviceCfg", lambda: cpu_device_cfg
77+
)
78+
restored = KinematicsLoaderCfg(**saved, device_cfg=cpu_device_cfg)
79+
np.testing.assert_allclose(
80+
restored.extra_links["sensor"].fixed_transform, link.fixed_transform, atol=1e-6
81+
)
82+
assert restored.extra_links["sensor"].joint_type == JointType.FIXED
83+
assert config.extra_links["sensor"] is link
84+
assert config.cspace.device_cfg is cpu_device_cfg
85+
assert builder._cspace_config["device_cfg"] is cpu_device_cfg
86+
87+
2388
def default_fit_type() -> SphereFitType:
2489
"""Get default fit type."""
2590
return SphereFitType.MORPHIT

‎curobo/tests/_src/types/test_robot_config.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66

77
# Standard Library
88
from copy import deepcopy
9+
from pathlib import Path
910

1011
# Third Party
1112
import pytest
1213
import torch
14+
import yaml
1315

1416
# CuRobo
1517
from curobo._src.robot.kinematics.kinematics import KinematicsCfg
@@ -20,6 +22,32 @@
2022
from curobo._src.util_file import get_assets_path, get_robot_configs_path, join_path, load_yaml
2123

2224

25+
@pytest.mark.parametrize("load_dynamics", [False, True])
26+
def test_write_config_roundtrip(
27+
tmp_path: Path, cpu_device_cfg: DeviceCfg, load_dynamics: bool
28+
) -> None:
29+
"""Safe YAML reloads into a robot and writing leaves runtime objects intact."""
30+
data = load_yaml(join_path(get_robot_configs_path(), "simple_mimic_robot.yml"))["robot_cfg"]
31+
data["kinematics"]["lock_joints"] = None
32+
data["load_dynamics"] = load_dynamics
33+
robot = RobotCfg.create(data, device_cfg=cpu_device_cfg)
34+
kinematics, dynamics = robot.kinematics, robot.dynamics
35+
output_path = tmp_path / "robot.yaml"
36+
robot.write_config(str(output_path))
37+
saved = yaml.safe_load(output_path.read_text())
38+
assert saved["load_dynamics"] is load_dynamics
39+
assert "device_cfg" not in saved
40+
assert "device_cfg" not in saved["kinematics"]["cspace"]
41+
restored = RobotCfg.create(saved, device_cfg=cpu_device_cfg)
42+
assert restored.cspace.joint_names == robot.cspace.joint_names
43+
assert (restored.dynamics is not None) is load_dynamics
44+
torch.testing.assert_close(
45+
restored.cspace.default_joint_position, robot.cspace.default_joint_position
46+
)
47+
assert robot.kinematics is kinematics
48+
assert robot.dynamics is dynamics
49+
50+
2351
def test_cspace_config():
2452
cspace_config = CSpaceParams(
2553
["j0", "j1", "j2", "j3"],

‎curobo/tests/_src/util/test_config_io.py‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55
# Standard Library
66
import os
77
from pathlib import Path
8+
from typing import Callable
89

910
# Third Party
11+
import pytest
12+
import yaml
13+
1014
# CuRobo
1115
from curobo._src.util.config_io import (
1216
copy_file_to_path,
@@ -21,6 +25,7 @@
2125
join_path,
2226
load_yaml,
2327
merge_dict_a_into_b,
28+
resolve_config,
2429
write_yaml,
2530
)
2631

@@ -68,6 +73,42 @@ def test_join_path_nested_paths(self):
6873

6974

7075
class TestYaml:
76+
@pytest.mark.parametrize("loader", [load_yaml, resolve_config])
77+
@pytest.mark.parametrize(
78+
"payload", ["!!python/tuple [1, 2]", "!!python/object/apply:builtins.str [42]"]
79+
)
80+
def test_reject_python_tags(
81+
self, tmp_path: Path, loader: Callable[[str], dict], payload: str
82+
) -> None:
83+
"""Configuration entry points reject Python-specific YAML tags."""
84+
yaml_file = tmp_path / "python.yaml"
85+
yaml_file.write_text(payload)
86+
with pytest.raises(yaml.constructor.ConstructorError):
87+
loader(str(yaml_file))
88+
89+
def test_scientific_notation(self, tmp_path: Path) -> None:
90+
"""Retain scientific-notation parsing with the safe loader."""
91+
yaml_file = tmp_path / "floats.yaml"
92+
yaml_file.write_text("small: 1e-3\nlarge: 2E3\nnegative: -4e-2\n")
93+
assert load_yaml(str(yaml_file)) == {"small": 0.001, "large": 2000.0, "negative": -0.04}
94+
95+
def test_write_plain_sequences(self, tmp_path: Path) -> None:
96+
"""Tuples are written as portable YAML sequences without Python tags."""
97+
yaml_file = tmp_path / "sequences.yaml"
98+
write_yaml({"pose": (1.0, 2.0, 3.0), "enabled": True}, str(yaml_file))
99+
assert yaml.safe_load(yaml_file.read_text()) == {
100+
"pose": [1.0, 2.0, 3.0],
101+
"enabled": True,
102+
}
103+
104+
def test_reject_objects_before_overwriting(self, tmp_path: Path) -> None:
105+
"""Unsupported objects fail without truncating an existing configuration."""
106+
yaml_file = tmp_path / "output.yaml"
107+
yaml_file.write_text("original: true\n")
108+
with pytest.raises(yaml.representer.RepresenterError):
109+
write_yaml({"runtime_object": object()}, str(yaml_file))
110+
assert yaml_file.read_text() == "original: true\n"
111+
71112
def test_load_yaml_from_file(self, tmp_path):
72113
yaml_file = tmp_path / "test.yaml"
73114
yaml_file.write_text("key: value\nnum: 42\n")
@@ -182,4 +223,3 @@ def test_create_dir(self, tmp_path):
182223
create_dir_if_not_exists(str(new_dir))
183224
assert new_dir.exists()
184225
assert new_dir.is_dir()
185-

‎curobo/tests/_src/util/test_usd_writer_robot.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -674,7 +674,7 @@ def test_write_trajectory_with_empty_mesh_links(
674674
# Save modified config
675675
import yaml
676676
with open(config_path, "w") as f:
677-
yaml.dump({"robot_cfg": robot_cfg}, f)
677+
yaml.safe_dump({"robot_cfg": robot_cfg}, f)
678678

679679
output_path = tmp_path / "no_mesh_trajectory.usd"
680680

@@ -911,4 +911,3 @@ def test_get_robot_prims_with_nested_structure(self, tmp_path):
911911
assert "base_joint" in joint_prims
912912
# Geometry prim should not be in link_prims even though it matches base_link
913913
assert link_prims["base_link"].GetPath().pathString == f"{robot_base}/base_link"
914-

0 commit comments

Comments
 (0)