Download scripts/validate_models.py from kaweees/unitree_model: direct link, hf CLI and curl.
- Browser
- Download file 7.96 kB
-
https://huggingface.co/datasets/kaweees/unitree_model/resolve/main/scripts/validate_models.py
- Command line
-
hf download hf://datasets/kaweees/unitree_model/scripts/validate_models.py
-
curl -L -o validate_models.py https://huggingface.co/datasets/kaweees/unitree_model/resolve/main/scripts/validate_models.py
7.96 kB
| """Independently check USD kinematics, masses, active joints and dependencies.""" | |
| import json, math, pathlib | |
| import xml.etree.ElementTree as ET | |
| import numpy as np | |
| from pxr import Gf, Usd, UsdGeom, UsdPhysics, UsdUtils | |
| ROOT = pathlib.Path(__file__).resolve().parents[1] | |
| def origin_matrix(node): | |
| node = node.find('origin') | |
| xyz = [float(x) for x in node.get('xyz', '0 0 0').split()] if node is not None else [0, 0, 0] | |
| rpy = [float(x) for x in node.get('rpy', '0 0 0').split()] if node is not None else [0, 0, 0] | |
| m = Gf.Matrix4d(1) | |
| rotation = Gf.Matrix4d(1) | |
| for axis, angle in zip((Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()), rpy): | |
| rotation = rotation * Gf.Matrix4d(Gf.Rotation(axis, math.degrees(angle)), Gf.Vec3d(0)) | |
| m.SetTranslate(Gf.Vec3d(*xyz)) | |
| return rotation * m | |
| def check_model(item): | |
| path = ROOT / item['usd'] | |
| stage = Usd.Stage.Open(str(path)) | |
| assert stage and stage.GetDefaultPrim(), item['id'] | |
| _, _, unresolved = UsdUtils.ComputeAllDependencies(str(path)) | |
| assert not unresolved, (item['id'], unresolved) | |
| robot = ET.parse(path.parent / 'input.urdf').getroot() | |
| link_nodes = {n.get('name'): n for n in robot.findall('link')} | |
| links = set(link_nodes) | |
| joints = robot.findall('joint') | |
| children = {n.find('child').get('link') for n in joints} | |
| poses = {n: Gf.Matrix4d(1) for n in links - children} | |
| pending = list(joints) | |
| while pending: | |
| progress = False | |
| for j in pending[:]: | |
| parent = j.find('parent').get('link') | |
| if parent in poses: | |
| poses[j.find('child').get('link')] = origin_matrix(j) * poses[parent] | |
| pending.remove(j) | |
| progress = True | |
| assert progress, ('Cyclic or disconnected source graph', item['id']) | |
| cache = UsdGeom.XformCache() | |
| checked = 0 | |
| max_error = 0.0 | |
| inertias_checked = 0 | |
| max_inertia_error = 0.0 | |
| for p in stage.Traverse(): | |
| if not p.HasAPI(UsdPhysics.RigidBodyAPI): continue | |
| name = p.GetDisplayName() or p.GetName() | |
| assert name in poses, (item['id'], name) | |
| actual = cache.GetLocalToWorldTransform(p) | |
| error = max(abs(actual[i][j] - poses[name][i][j]) for i in range(4) for j in range(4)) | |
| max_error = max(max_error, error) | |
| assert error < 1e-5, ('Forward kinematics mismatch', item['id'], name, error) | |
| inertial = link_nodes[name].find('inertial') | |
| if inertial is not None: | |
| api = UsdPhysics.MassAPI(p) | |
| expected_mass = float(inertial.find('mass').get('value')) | |
| assert math.isclose(api.GetMassAttr().Get(), expected_mass, rel_tol=1e-5, abs_tol=1e-8), ('Link mass mismatch', item['id'], name) | |
| offset = origin_matrix(inertial) | |
| assert np.allclose(api.GetCenterOfMassAttr().Get(), offset.ExtractTranslation(), rtol=1e-5, atol=1e-7), ('Center of mass mismatch', item['id'], name) | |
| tensor = inertial.find('inertia') | |
| expected = np.array([[float(tensor.get('i'+a+b, tensor.get('i'+b+a, '0'))) for b in 'xyz'] for a in 'xyz']) | |
| rotation = np.array(offset.ExtractRotationMatrix()) | |
| expected = rotation.T @ expected @ rotation | |
| axes = api.GetPrincipalAxesAttr().Get() | |
| rotation = np.array(Gf.Matrix3d(Gf.Rotation(Gf.Quatd(axes)))) | |
| actual_tensor = rotation.T @ np.diag(api.GetDiagonalInertiaAttr().Get()) @ rotation | |
| error = float(np.max(np.abs(actual_tensor - expected))) | |
| # Principal axes are stored as float quaternions; compare at tensor | |
| # scale so roundoff in near-zero off-diagonal terms is meaningful. | |
| tolerance = max(1e-9, float(np.max(np.abs(expected))) * 1e-5) | |
| assert error <= tolerance, ('Link inertia mismatch', item['id'], name, error, tolerance) | |
| max_inertia_error = max(max_inertia_error, error) | |
| inertias_checked += 1 | |
| checked += 1 | |
| source_mass = sum(float(n.get('value')) for n in robot.findall('link/inertial/mass')) | |
| usd_mass = sum(UsdPhysics.MassAPI(p).GetMassAttr().Get() or 0 for p in stage.Traverse() if p.HasAPI(UsdPhysics.MassAPI)) | |
| assert abs(source_mass - usd_mass) < max(1e-5, source_mass * 1e-5), item['id'] | |
| source_active = sum(j.get('type') in ('revolute', 'continuous', 'prismatic') for j in joints) | |
| usd_active = sum(p.IsA(UsdPhysics.RevoluteJoint) or p.IsA(UsdPhysics.PrismaticJoint) for p in stage.Traverse()) | |
| assert source_active == usd_active, (item['id'], source_active, usd_active) | |
| joint_nodes = {j.get('name'): j for j in joints} | |
| axes_checked = limits_checked = mimic_checked = 0 | |
| for p in stage.Traverse(): | |
| for rel in p.GetRelationships(): | |
| if 'mimic' in rel.GetName().lower(): | |
| for target in rel.GetTargets(): | |
| assert stage.GetPrimAtPath(target), ('Dangling mimic reference', item['id'], str(p.GetPath()), str(target)) | |
| mimic_checked += 1 | |
| if not (p.IsA(UsdPhysics.RevoluteJoint) or p.IsA(UsdPhysics.PrismaticJoint)): continue | |
| name = p.GetDisplayName() or p.GetName() | |
| assert name in joint_nodes, ('Unknown joint', item['id'], name) | |
| node = joint_nodes[name] | |
| api = UsdPhysics.Joint(p) | |
| axis_api = UsdPhysics.RevoluteJoint(p) if p.IsA(UsdPhysics.RevoluteJoint) else UsdPhysics.PrismaticJoint(p) | |
| axis = {'X': Gf.Vec3d.XAxis(), 'Y': Gf.Vec3d.YAxis(), 'Z': Gf.Vec3d.ZAxis()}[axis_api.GetAxisAttr().Get()] | |
| body = stage.GetPrimAtPath(api.GetBody1Rel().GetTargets()[0]) | |
| actual_axis = cache.GetLocalToWorldTransform(body).TransformDir(Gf.Rotation(Gf.Quatd(api.GetLocalRot1Attr().Get())).TransformDir(axis)).GetNormalized() | |
| src_axis = node.find('axis') | |
| expected_axis = Gf.Vec3d(*[float(x) for x in (src_axis.get('xyz', '1 0 0') if src_axis is not None else '1 0 0').split()]) | |
| expected_axis = poses[node.find('child').get('link')].TransformDir(expected_axis).GetNormalized() | |
| assert np.allclose(actual_axis, expected_axis, atol=1e-5), ('Joint axis mismatch', item['id'], name) | |
| axes_checked += 1 | |
| limit = node.find('limit') | |
| if node.get('type') != 'continuous' and limit is not None: | |
| scale = 180 / math.pi if node.get('type') == 'revolute' else 1 | |
| for key, value in [('lower', axis_api.GetLowerLimitAttr().Get()), ('upper', axis_api.GetUpperLimitAttr().Get())]: | |
| if limit.get(key) is not None: | |
| assert math.isclose(value, float(limit.get(key))*scale, rel_tol=1e-5, abs_tol=1e-5), ('Joint limit mismatch', item['id'], name, key) | |
| limits_checked += 1 | |
| return {'id': item['id'], 'passed': True, 'checked_body_poses': checked, | |
| 'max_fk_matrix_error': max_error, 'active_joints_preserved': source_active, | |
| 'checked_link_inertias': inertias_checked, 'max_inertia_tensor_error': max_inertia_error, | |
| 'checked_joint_axes': axes_checked, 'checked_joint_limits': limits_checked, | |
| 'resolved_mimic_references': mimic_checked, | |
| 'total_mass_preserved_kg': source_mass, 'unresolved_dependencies': []} | |
| if __name__ == '__main__': | |
| manifest = json.loads((ROOT / 'manifest.json').read_text()) | |
| assert all(m['status'] == 'converted' for m in manifest['models']) | |
| report = [check_model(m) for m in manifest['models']] | |
| output = {'checks': 'USD composition; independent URDF forward kinematics for every rigid body; per-link mass, center of mass and inertia tensors; active joint counts; world-space joint axes and limits; mimic relationship targets; total mass; dependency resolution', | |
| 'isaac_sim_runtime_tested': False, 'models': report, | |
| 'passed_models': len(report), 'failed_models': 0} | |
| (ROOT / 'validation_report.json').write_text(json.dumps(output, indent=2) + '\n') | |
| print('PASS:', len(report), 'models;', sum(m['checked_body_poses'] for m in report), 'body poses') | |