322 lines
12 KiB
Python
322 lines
12 KiB
Python
"""Bounded native P2 matrix using the production autonomous command path."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import sys
|
|
import time
|
|
import traceback
|
|
from contextlib import ExitStack
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
parser.add_argument("--reservation", type=Path, required=True)
|
|
parser.add_argument("--case", action="append", dest="case_ids")
|
|
parser.add_argument("--profile", choices=("control", "sweep", "transition"), default="control")
|
|
parser.add_argument("--contact-sample-hz", type=int, default=0, choices=(0, 1, 5, 10, 60))
|
|
args = parser.parse_args()
|
|
receipt = json.loads(args.reservation.read_text(encoding="utf-8-sig"))
|
|
if receipt["state"] != "reserved" or not receipt["owner_id"].startswith("airun-"):
|
|
raise ValueError("Existing Core simulation reservation required")
|
|
args.output.mkdir(parents=True, exist_ok=False)
|
|
root = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(root / "src"))
|
|
|
|
from control_qualification import ( # noqa: E402
|
|
CRITERIA,
|
|
DT,
|
|
PHASES,
|
|
SCHEMA,
|
|
angle_delta,
|
|
phase_metrics,
|
|
specifications,
|
|
)
|
|
from motion_control import RoverMotionControl # noqa: E402
|
|
|
|
from k1link.simulation.ai_polygon.robots import select_robot # noqa: E402
|
|
from k1link.simulation.ai_polygon.run_inputs import legacy_run_inputs # noqa: E402
|
|
from k1link.simulation.ai_polygon.run_robot import configure_robot # noqa: E402
|
|
|
|
if args.profile == "transition":
|
|
from control_qualification import TRANSITION_PHASES as PHASES
|
|
|
|
if args.profile == "sweep":
|
|
from sweep_qualification import CRITERIA, PHASES, SCHEMA
|
|
from sweep_qualification import phase_metrics as sweep_metrics
|
|
|
|
|
|
def write(name, value):
|
|
(args.output / name).write_text(json.dumps(value, indent=2, allow_nan=False), encoding="utf-8")
|
|
|
|
|
|
base = select_robot("dcd006-v020")
|
|
cases = []
|
|
if args.case_ids and set(args.case_ids) - {s["id"] for s in specifications()}:
|
|
raise ValueError("Unknown control matrix case")
|
|
for spec in specifications():
|
|
if args.case_ids and spec["id"] not in args.case_ids:
|
|
continue
|
|
robot, config = configure_robot(
|
|
base,
|
|
dict(
|
|
max_speed_mps=spec["speed_mps"],
|
|
base_mass_kg=100,
|
|
payload_mass_kg=spec["payload_kg"],
|
|
payload_height_m=0.9,
|
|
),
|
|
)
|
|
run = {
|
|
"world": {
|
|
"settings": {"camera_height_m": 0.8, "max_speed_mps": spec["speed_mps"], "route_xy": []}
|
|
},
|
|
"request": {"composition": None},
|
|
}
|
|
cases.append(
|
|
{
|
|
**spec,
|
|
"robot": robot,
|
|
"configuration": config,
|
|
"execution_inputs": legacy_run_inputs(run, robot),
|
|
}
|
|
)
|
|
source_paths = [
|
|
Path(__file__),
|
|
*(
|
|
Path(__file__).with_name(n)
|
|
for n in (
|
|
"control_qualification.py",
|
|
"motion_control.py",
|
|
"rover_profile.py",
|
|
"tracked_rover.py",
|
|
"track_dynamics.py",
|
|
)
|
|
),
|
|
root / "src/k1link/fleet/differential_drive.py",
|
|
root / "src/k1link/simulation/ai_polygon/run_robot.py",
|
|
root / "src/k1link/simulation/ai_polygon/run_inputs.py",
|
|
Path(__file__).parent / "robots/dcd006-v020.json",
|
|
]
|
|
if args.profile == "sweep":
|
|
source_paths.extend(
|
|
(
|
|
Path(__file__).with_name("sweep_qualification.py"),
|
|
Path(__file__).parent / "navigation/footprint.py",
|
|
)
|
|
)
|
|
manifest = dict(
|
|
schema_version=SCHEMA,
|
|
profile=args.profile,
|
|
run_id=receipt["owner_id"],
|
|
utc=datetime.now(UTC).isoformat(),
|
|
monotonic=time.monotonic(),
|
|
dt=DT,
|
|
phases=PHASES,
|
|
criteria=CRITERIA,
|
|
cases=cases,
|
|
localization="simulator-oracle",
|
|
perception="none; isolates controller and contact",
|
|
scope="flat metric ground, 60x6 m per case; synthetic friction, no real hardware",
|
|
wall_budget_seconds=480,
|
|
contact_sample_hz=args.contact_sample_hz,
|
|
complete_matrix=args.case_ids is None,
|
|
source_sha256={
|
|
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
|
|
for p in source_paths
|
|
},
|
|
)
|
|
write("acceptance.json", manifest) # Frozen before native startup or first measurement.
|
|
|
|
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 pxr import Gf, UsdGeom, UsdPhysics, UsdShade
|
|
from rover_profile import create_rover, open_drive
|
|
|
|
stage = omni.usd.get_context().get_stage()
|
|
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
|
|
UsdGeom.SetStageMetersPerUnit(stage, 1)
|
|
runtime = []
|
|
for index, case in enumerate(cases):
|
|
y, ground, rover = index * 10.0, f"/World/Ground{index}", f"/World/Rover{index}"
|
|
material = UsdShade.Material.Define(stage, f"/World/Material{index}")
|
|
physics = UsdPhysics.MaterialAPI.Apply(material.GetPrim())
|
|
physics.CreateStaticFrictionAttr(case["static_friction"])
|
|
physics.CreateDynamicFrictionAttr(case["dynamic_friction"])
|
|
floor = UsdGeom.Cube.Define(stage, ground)
|
|
floor.CreateSizeAttr(1)
|
|
floor.AddTranslateOp().Set(Gf.Vec3d(0, y, -0.1))
|
|
floor.AddScaleOp().Set(Gf.Vec3f(60, 6, 0.2))
|
|
UsdPhysics.CollisionAPI.Apply(floor.GetPrim())
|
|
UsdShade.MaterialBindingAPI.Apply(floor.GetPrim()).Bind(
|
|
material, UsdShade.Tokens.weakerThanDescendants, "physics"
|
|
)
|
|
create_rover(stage, [0, y, 0.30], 0, root_path=rover, document=case["robot"])
|
|
runtime.append(
|
|
dict(
|
|
root=rover,
|
|
ground=ground,
|
|
control=RoverMotionControl(case["robot"], case["speed_mps"]),
|
|
)
|
|
)
|
|
SimulationManager.setup_simulation(dt=DT, device="cpu")
|
|
omni.timeline.get_timeline_interface().play()
|
|
for _ in range(20):
|
|
app.update()
|
|
|
|
def sample(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())
|
|
rotation = np.asarray(Gf.Matrix3d(Gf.Quatd(float(q[0]), Gf.Vec3d(*map(float, q[1:]))))).T
|
|
return dict(
|
|
position=xyz.tolist(),
|
|
quaternion_wxyz=q.tolist(),
|
|
velocity=linear.tolist(),
|
|
angular_velocity=angular.tolist(),
|
|
heading=math.atan2(float(rotation[1, 0]), float(rotation[0, 0])),
|
|
forward_mps=float(np.dot(linear, rotation[:, 0])),
|
|
pitch_rps=float(np.dot(angular, rotation[:, 1])),
|
|
yaw_rps=float(angular[2]),
|
|
)
|
|
|
|
for case, live in zip(cases, runtime, strict=True):
|
|
live["drive"] = open_drive(
|
|
live["root"], contact_filter_paths=[live["ground"]], document=case["robot"]
|
|
)
|
|
live["previous"] = sample(live["drive"])
|
|
live["phases"] = []
|
|
start = time.monotonic()
|
|
with ExitStack() as files:
|
|
output = files.enter_context((args.output / "motion.jsonl").open("w", encoding="utf-8"))
|
|
contacts = (
|
|
files.enter_context((args.output / "contacts.jsonl").open("w", encoding="utf-8"))
|
|
if args.contact_sample_hz
|
|
else None
|
|
)
|
|
for name, duration, multiplier, turn in PHASES:
|
|
traces = [[] for _ in cases]
|
|
for live in runtime:
|
|
live["phase_origin"] = live["previous"]["position"]
|
|
for frame in range(round(duration / DT)):
|
|
if time.monotonic() - start > manifest["wall_budget_seconds"]:
|
|
raise TimeoutError("Control matrix exceeded bounded physics time")
|
|
for case, live in zip(cases, runtime, strict=True):
|
|
velocity = multiplier * case["speed_mps"]
|
|
prior = live["previous"]
|
|
command = live["control"].step(
|
|
velocity, turn, DT, prior["forward_mps"], prior["pitch_rps"]
|
|
)
|
|
live["command"] = command
|
|
live["drive"].command(*command)
|
|
live["drive"].step(DT)
|
|
SimulationManager.step(steps=1)
|
|
for case, live, rows in zip(cases, runtime, traces, strict=True):
|
|
current, prior = sample(live["drive"]), live["previous"]
|
|
model = live["drive"].metrics
|
|
row = {
|
|
**current,
|
|
"pre_step": prior,
|
|
"case": case["id"],
|
|
"phase_origin": live["phase_origin"],
|
|
"phase": name,
|
|
"phase_seconds": (frame + 1) * DT,
|
|
"dt": DT,
|
|
"monotonic": time.monotonic(),
|
|
"request": [multiplier * case["speed_mps"], turn],
|
|
"nominal": list(
|
|
live["control"].envelope.drive.applied.twist(
|
|
case["robot"]["physics"]["track_width_m"]
|
|
)
|
|
),
|
|
"applied": list(live["command"]),
|
|
"belt_mps": model["belt_mps"],
|
|
"held_sides": model["held_sides"],
|
|
"normal_load_n": model["normal_load_n"],
|
|
"distance_step_m": math.dist(
|
|
current["position"][:2], prior["position"][:2]
|
|
),
|
|
"turn_step_rad": angle_delta(current["heading"], prior["heading"]),
|
|
"acceleration_mps2": (current["forward_mps"] - prior["forward_mps"]) / DT,
|
|
}
|
|
output.write(json.dumps(row, allow_nan=False) + "\n")
|
|
if contacts is not None and frame % round(1 / DT / args.contact_sample_hz) == 0:
|
|
contacts.write(
|
|
json.dumps(
|
|
dict(
|
|
case=case["id"],
|
|
phase=name,
|
|
phase_seconds=frame * DT,
|
|
dt=DT,
|
|
pre_step=prior,
|
|
post_step=current,
|
|
target_sides=live["drive"].target.tolist(),
|
|
contact=model,
|
|
),
|
|
allow_nan=False,
|
|
)
|
|
+ "\n"
|
|
)
|
|
rows.append(row)
|
|
live["previous"] = current
|
|
for case, live, rows in zip(cases, runtime, traces, strict=True):
|
|
live["phases"].append(
|
|
sweep_metrics(rows, case["robot"]["physics"])
|
|
if args.profile == "sweep"
|
|
else phase_metrics(rows)
|
|
)
|
|
print(json.dumps({"phase": name, "elapsed_s": time.monotonic() - start}), flush=True)
|
|
results = [
|
|
{
|
|
"id": case["id"],
|
|
"phases": live["phases"],
|
|
"passed": all(p["passed"] for p in live["phases"]),
|
|
}
|
|
for case, live in zip(cases, runtime, strict=True)
|
|
]
|
|
report = dict(
|
|
schema_version=SCHEMA,
|
|
run_id=receipt["owner_id"],
|
|
utc=datetime.now(UTC).isoformat(),
|
|
monotonic=time.monotonic(),
|
|
wall_seconds=time.monotonic() - start,
|
|
complete_matrix=args.case_ids is None,
|
|
cases=results,
|
|
acceptance_sha256=hashlib.sha256(
|
|
(args.output / "acceptance.json").read_bytes()
|
|
).hexdigest(),
|
|
passed=all(c["passed"] for c in results),
|
|
)
|
|
write("report.json", report)
|
|
write(
|
|
"manifest.json",
|
|
{
|
|
"files": {
|
|
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
|
for p in args.output.iterdir()
|
|
if p.is_file()
|
|
}
|
|
},
|
|
)
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"passed": report["passed"],
|
|
"cases": [{"id": c["id"], "passed": c["passed"]} for c in results],
|
|
}
|
|
),
|
|
flush=True,
|
|
)
|
|
except BaseException:
|
|
traceback.print_exc()
|
|
sys.stderr.flush()
|
|
raise
|
|
finally:
|
|
app.close()
|