Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
"""Bounded native contact invariants; synthetic fixtures, no physical devices."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(root / "src"))
|
||||
|
||||
from isaacsim import SimulationApp # noqa: E402
|
||||
|
||||
app = SimulationApp({"headless": True, "hide_ui": True, "multi_gpu": False})
|
||||
try:
|
||||
import numpy as np
|
||||
import omni.timeline
|
||||
import omni.usd
|
||||
from isaacsim.core.simulation_manager import SimulationManager
|
||||
from motion_control import DriveEnvelope
|
||||
from pxr import Gf, UsdGeom, UsdPhysics, UsdShade
|
||||
from rover_profile import ROBOT_DOCUMENT, create_rover, open_drive
|
||||
|
||||
stage = omni.usd.get_context().get_stage()
|
||||
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
|
||||
UsdGeom.SetStageMetersPerUnit(stage, 1)
|
||||
cases = {}
|
||||
names = ("coast", "brake", "pivot", "ice", "air", "slope", "gap")
|
||||
for index, name in enumerate(names):
|
||||
y = index * 10.0
|
||||
angle = math.radians(10) if name == "slope" else 0
|
||||
normal = [-math.sin(angle), 0, math.cos(angle)]
|
||||
surface = UsdShade.Material.Define(stage, f"/World/Material_{name}")
|
||||
material = UsdPhysics.MaterialAPI.Apply(surface.GetPrim())
|
||||
friction = 0.0 if name == "ice" else 0.8
|
||||
material.CreateStaticFrictionAttr(friction)
|
||||
material.CreateDynamicFrictionAttr(friction)
|
||||
filters = []
|
||||
patches = [(-0.35, 0.20), (0.20, 0.20)] if name == "gap" else [(0, 12)]
|
||||
for part, (x, length) in enumerate(patches):
|
||||
path = f"/World/Ground_{name}_{part}"
|
||||
floor = UsdGeom.Cube.Define(stage, path)
|
||||
floor.CreateSizeAttr(1)
|
||||
floor.AddTranslateOp().Set(Gf.Vec3d(x, y, -0.1 / math.cos(angle)))
|
||||
floor.AddRotateYOp().Set(-math.degrees(angle))
|
||||
floor.AddScaleOp().Set(Gf.Vec3f(length, 3, 0.2))
|
||||
UsdPhysics.CollisionAPI.Apply(floor.GetPrim())
|
||||
UsdShade.MaterialBindingAPI.Apply(floor.GetPrim()).Bind(
|
||||
surface, UsdShade.Tokens.weakerThanDescendants, "physics"
|
||||
)
|
||||
filters.append(path)
|
||||
path = f"/World/Rover_{name}"
|
||||
create_rover(stage, [0, y, 10 if name == "air" else 0.3], 0, normal, path, model="tracks")
|
||||
cases[name] = {"root": path, "filters": filters, "rows": [], "envelope": DriveEnvelope()}
|
||||
|
||||
SimulationManager.setup_simulation(dt=1 / 60, device="cpu")
|
||||
omni.timeline.get_timeline_interface().play()
|
||||
for _ in range(20):
|
||||
app.update()
|
||||
for case in cases.values():
|
||||
case["drive"] = open_drive(
|
||||
case["root"], model="tracks", contact_filter_paths=case["filters"]
|
||||
)
|
||||
start = time.monotonic()
|
||||
dt = 1 / 60
|
||||
with (args.output / "motion.jsonl").open("w", encoding="utf-8") as output:
|
||||
for frame in range(480):
|
||||
if time.monotonic() - start > 180:
|
||||
raise TimeoutError("Contact suite exceeded 180 seconds")
|
||||
seconds = frame * dt
|
||||
for name, case in cases.items():
|
||||
velocity, turn, mode = 0.0, 0.0, None
|
||||
if name in {"coast", "brake"}:
|
||||
velocity = 0.3 if seconds < 3 else 0
|
||||
mode = name if seconds >= 3 else None
|
||||
elif name == "pivot":
|
||||
turn = 0.35 if seconds < 5 else 0
|
||||
elif name in {"ice", "air"}:
|
||||
velocity = 0.3
|
||||
elif name == "slope":
|
||||
velocity = 0.15 if seconds < 6 else 0
|
||||
mode = "brake" if seconds >= 6 else None
|
||||
drive = case["drive"]
|
||||
drive.command(*case["envelope"].step(velocity, turn, dt), mode=mode)
|
||||
drive.step(dt)
|
||||
SimulationManager.step(steps=1)
|
||||
for name, case in cases.items():
|
||||
drive = case["drive"]
|
||||
xyz, q = (v.numpy()[0] for v in drive.body.get_world_poses())
|
||||
linear, angular = (v.numpy()[0] for v in drive.body.get_velocities())
|
||||
forces, _, counts, offsets = (
|
||||
v.numpy() for v in drive.body.get_friction_data(dt=dt)
|
||||
)
|
||||
native_friction = sum(
|
||||
float(np.linalg.norm(forces[i]))
|
||||
for offset, count in zip(offsets.flat, counts.flat, strict=True)
|
||||
for i in range(int(offset), int(offset + count))
|
||||
)
|
||||
row = {
|
||||
"case": name,
|
||||
"frame": frame,
|
||||
"seconds": seconds,
|
||||
"monotonic": time.monotonic(),
|
||||
"position": xyz.tolist(),
|
||||
"heading": math.atan2(
|
||||
2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] ** 2 + q[3] ** 2)
|
||||
),
|
||||
"velocity": linear.tolist(),
|
||||
"angular_velocity": angular.tolist(),
|
||||
"native_friction_n": native_friction,
|
||||
"drive": drive.metrics,
|
||||
}
|
||||
case["rows"].append(row)
|
||||
output.write(json.dumps(row, allow_nan=False) + "\n")
|
||||
|
||||
phases = []
|
||||
|
||||
def check(name, passed, **metrics):
|
||||
phases.append({"name": name, "passed": bool(passed), **metrics})
|
||||
|
||||
distances = {}
|
||||
for name in ("coast", "brake"):
|
||||
rows = cases[name]["rows"]
|
||||
distances[name] = rows[-1]["position"][0] - rows[179]["position"][0]
|
||||
check(
|
||||
"brake-versus-coast",
|
||||
0 < distances["brake"] < distances["coast"] * 0.6,
|
||||
distance_m=distances,
|
||||
)
|
||||
coast = cases["coast"]["rows"][180:]
|
||||
check("coast-releases-motor", all(r["drive"]["motor_force_n"] == [0, 0] for r in coast))
|
||||
pivot = cases["pivot"]["rows"]
|
||||
angle = pivot[299]["heading"] - pivot[0]["heading"]
|
||||
drift = math.dist(pivot[299]["position"][:2], pivot[0]["position"][:2])
|
||||
check(
|
||||
"opposed-tracks-pivot", angle > 0.6 and drift < 0.3, heading_change_rad=angle, drift_m=drift
|
||||
)
|
||||
ice = cases["ice"]["rows"]
|
||||
ice_distance = math.dist(ice[-1]["position"][:2], ice[0]["position"][:2])
|
||||
check(
|
||||
"zero-friction-no-traction",
|
||||
ice_distance < 0.005
|
||||
and all(np.linalg.norm(r["drive"]["force_n"]) < 1e-6 for r in ice)
|
||||
and min(ice[-1]["drive"]["belt_mps"]) > 0.25,
|
||||
drift_m=ice_distance,
|
||||
)
|
||||
air = cases["air"]["rows"][:30]
|
||||
check(
|
||||
"airborne-no-traction",
|
||||
all(
|
||||
sum(r["drive"]["normal_load_n"]) == 0 and np.linalg.norm(r["drive"]["force_n"]) == 0
|
||||
for r in air
|
||||
)
|
||||
and math.dist(air[-1]["position"][:2], air[0]["position"][:2]) < 0.005,
|
||||
)
|
||||
slope = cases["slope"]["rows"]
|
||||
advance = slope[359]["position"][0] - slope[0]["position"][0]
|
||||
climb = slope[359]["position"][2] - slope[0]["position"][2]
|
||||
check("ten-degree-ascent", advance > 0.3 and climb > 0.05, advance_m=advance, climb_m=climb)
|
||||
speed = float(np.linalg.norm(slope[-1]["velocity"]))
|
||||
check("slope-braking", speed < 0.03, final_speed_mps=speed)
|
||||
gap = cases["gap"]["rows"]
|
||||
supports = [p for r in gap for p in r["drive"]["supports"]]
|
||||
check(
|
||||
"gap-has-no-invented-support",
|
||||
len(supports) > 0
|
||||
and all(
|
||||
-0.451 <= p["point"][0] <= -0.249 or 0.099 <= p["point"][0] <= 0.301 for p in supports
|
||||
),
|
||||
support_samples=len(supports),
|
||||
)
|
||||
all_rows = [r for case in cases.values() for r in case["rows"]]
|
||||
normal_error = max(float(np.linalg.norm(np.subtract(
|
||||
r['drive']['native_normal_force_n'], r['drive']['reported_normal_force_n'])))
|
||||
for r in all_rows)
|
||||
check('detailed-contact-matches-native-aggregate', normal_error < 0.05,
|
||||
maximum_force_error_n=normal_error)
|
||||
settled_rows = [
|
||||
r
|
||||
for name, case in cases.items()
|
||||
if name != "air"
|
||||
for r in case["rows"]
|
||||
if not any(r["drive"]["held_sides"])
|
||||
]
|
||||
maximum = max(r["native_friction_n"] for r in settled_rows)
|
||||
check("moving-belt-native-friction", maximum < 0.01, maximum_native_friction_n=maximum)
|
||||
check("passive-contact", max(r["drive"]["slip_power_w"] for r in all_rows) <= 1e-6)
|
||||
source_paths = [
|
||||
Path(__file__),
|
||||
*(
|
||||
Path(__file__).with_name(n)
|
||||
for n in (
|
||||
"rover_profile.py",
|
||||
"motion_control.py",
|
||||
"tracked_rover.py",
|
||||
"track_dynamics.py",
|
||||
)
|
||||
),
|
||||
Path(__file__).parent / "robots/dcd006-v020.json",
|
||||
root / "src/k1link/fleet/differential_drive.py",
|
||||
]
|
||||
report = {
|
||||
"schema_version": "missioncore.track-contact-rig/v1",
|
||||
"utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"wall_seconds": time.monotonic() - start,
|
||||
"simulated_seconds": 8,
|
||||
"source_sha256": {
|
||||
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in source_paths
|
||||
},
|
||||
"robot": ROBOT_DOCUMENT,
|
||||
"phases": phases,
|
||||
"passed": all(p["passed"] for p in phases),
|
||||
"scope": (
|
||||
"Synthetic contact invariants; the air case qualifies only its first 0.5 s before "
|
||||
"impact. Settled belt native-friction tolerance 0.01 N (about 1e-5 body weight). "
|
||||
"Drop impact, reconstructed terrain and VESC are not qualified."
|
||||
),
|
||||
}
|
||||
(args.output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
manifest = {
|
||||
"utc": report["utc"],
|
||||
"files": {
|
||||
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in args.output.iterdir()
|
||||
if p.is_file()
|
||||
},
|
||||
}
|
||||
(args.output / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
||||
print(json.dumps({"passed": report["passed"], "phases": phases}), flush=True)
|
||||
except BaseException:
|
||||
traceback.print_exc()
|
||||
sys.stderr.flush()
|
||||
raise
|
||||
finally:
|
||||
app.close()
|
||||
Reference in New Issue
Block a user