File size: 5,354 Bytes
a84ddf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""Check the rc_ objects in Isaac Sim (PROD-120): rigid ones rest stably, the joints of the articulated ones behave.

    OMNI_KIT_ACCEPT_EULA=YES CUDA_VISIBLE_DEVICES=1 /data1/viet/venv/robodojo_client/bin/python dev_suite/robocurve/probe_objects.py

Rigid: dropped on a floor at its resting pose for 3 s: moved < 2 cm, tilted < 5 deg, not sunk. Articulations, base held
by a fixed joint as `fixed_base` does in RoboDojo (the carton is free): each joint is set to the middle of its range
and the sim runs 3 s. The drawer's spring and the lid's weight must bring them back to 0 (shut); the carton's bottom
flaps, lifted off the floor, must fall open. Writes dev_suite/robocurve/object_probe.json.
"""

from __future__ import annotations

import json
import math
import os
from pathlib import Path

from isaacsim import SimulationApp

HERE = Path(__file__).resolve().parent
OBJECTS = Path(os.environ.get("ROBOCURVE_OBJECTS", "/data1/viet/robocurve_objects"))
SPACING, SECONDS, DT = 1.0, 3.0, 0.004
EXPECT = {"rc_drawer_cabinet": "shut", "rc_lidded_bin": "shut", "rc_open_carton": "open"}


def main() -> None:
    app = SimulationApp({"headless": True})

    import numpy as np
    from isaacsim.core.api import World
    from isaacsim.core.prims import SingleArticulation, SingleRigidPrim
    from isaacsim.core.utils.stage import add_reference_to_stage, get_current_stage
    from pxr import Sdf, UsdPhysics

    world = World(physics_dt=DT, rendering_dt=DT * 10, stage_units_in_meters=1.0)
    world.scene.add_default_ground_plane(static_friction=1.0, dynamic_friction=1.0)
    rigid, arts = {}, {}
    names = [(k, n.name) for k in ("Rigid", "Articulation") for n in sorted((OBJECTS / k).iterdir())]
    for i, (kind, name) in enumerate(names):
        folder = OBJECTS / kind / name / "00000"
        meta = json.loads((folder / "metadata.json").read_text())
        z = -meta["active"]["place"]["up"]["projection_circle"]["center"][2] + 0.002
        lift = 0.15 if EXPECT.get(name) == "open" else 0.0  # the carton hangs in the air
        pos = np.array([(i % 6) * SPACING, (i // 6) * SPACING, z + lift])
        path = f"/World/{name}"
        add_reference_to_stage(str(folder / "object.usd"), path)
        if kind == "Rigid":
            body = SingleRigidPrim(path, name=name, translation=pos, orientation=np.array([1.0, 0, 0, 0]))
            body.set_mass(meta["physics"]["mass"])
            rigid[name] = (body, pos)
        else:
            stage = get_current_stage()
            base = next(p for p in stage.GetPrimAtPath(path).GetChildren() if p.HasAPI(UsdPhysics.RigidBodyAPI))
            fixed = UsdPhysics.FixedJoint.Define(stage, f"{path}/pin")  # held in place: fixed_base, or the carton held up
            fixed.CreateBody1Rel().SetTargets([base.GetPath()])
            fixed.CreateLocalPos0Attr().Set(tuple(float(v) for v in pos))
            # as RoboDojo's fix_root_link: the root, with its PhysX settings (no self-collision), moves to the parent
            parent = stage.GetPrimAtPath(path)
            base.RemoveAPI(UsdPhysics.ArticulationRootAPI)
            UsdPhysics.ArticulationRootAPI.Apply(parent)
            parent.AddAppliedSchema("PhysxArticulationAPI")
            parent.CreateAttribute("physxArticulation:enabledSelfCollisions", Sdf.ValueTypeNames.Bool).Set(False)
            art = SingleArticulation(path, name=name, translation=pos, orientation=np.array([1.0, 0, 0, 0]))
            arts[name] = world.scene.add(art)
    world.reset()
    for name, art in arts.items():
        lo, hi = art.dof_properties["lower"], art.dof_properties["upper"]
        if EXPECT[name] == "shut":
            art.set_joint_positions((lo + hi) / 2)
            art._articulation_view.set_joint_position_targets(np.zeros((1, art.num_dof)))  # RoboDojo resets the drive targets
    for _ in range(int(SECONDS / DT)):
        world.step(render=False)
    report = {}
    for name, (body, start) in rigid.items():
        pos, quat = (np.asarray(v, dtype=float) for v in body.get_world_pose())
        tilt = math.degrees(math.acos(max(-1.0, min(1.0, 1 - 2 * (quat[1] ** 2 + quat[2] ** 2)))))
        moved, sink = float(np.linalg.norm(pos[:2] - start[:2])), float(start[2] - pos[2])
        ok = bool(moved < 0.02 and tilt < 5 and -0.01 < sink < 0.01)
        report[name] = {"ok": ok, "moved": round(moved, 4), "tilt_deg": round(tilt, 1), "sink": round(sink, 4)}
        print(f"{name:22} {'ok ' if ok else 'BAD'} moved {moved:.3f} tilt {tilt:5.1f} sink {sink:+.3f}", flush=True)
    for name, art in arts.items():
        lo, hi = art.dof_properties["lower"], art.dof_properties["upper"]
        q = np.asarray(art.get_joint_positions(), dtype=float)
        ratio = np.abs(q) / np.maximum(np.abs(lo), np.abs(hi))  # 0 = at rest (shut), 1 = fully open
        ok = bool(np.all(ratio < 0.05) if EXPECT[name] == "shut" else np.all(ratio > 0.5))
        report[name] = {"ok": ok, "expect": EXPECT[name], "joints": art.dof_names, "open_ratio": ratio.round(3).tolist()}
        print(f"{name:22} {'ok ' if ok else 'BAD'} expect {EXPECT[name]}: {dict(zip(art.dof_names, ratio.round(3)))}", flush=True)
    (HERE / "object_probe.json").write_text(json.dumps(report, indent=1, sort_keys=True) + "\n")
    print(f"ok {sum(r['ok'] for r in report.values())}/{len(report)}")
    app.close()


if __name__ == "__main__":
    main()