Files
NODEDC_MISSION_CORE/simulation/ai-polygon/qualify_mobility.py
T
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00

130 lines
7.3 KiB
Python

"""Native mobility matrix using the production chassis/drive, no planner bypass.
This is a plant-characterization rig: commanded belts, PhysX contact and gravity.
It does not qualify autonomous stairs or certify the physical rover. Complete
source identities, model assumptions and every unsuccessful case are retained.
"""
import argparse
import hashlib
import json
import math
import sys
import time
from datetime import UTC, datetime
from pathlib import Path
p = argparse.ArgumentParser()
p.add_argument('--output', type=Path, required=True)
p.add_argument('--reservation-receipt', type=Path, required=True)
p.add_argument('--cases', nargs='*')
a = p.parse_args()
receipt = json.loads(a.reservation_receipt.read_text())
assert receipt['state'] == 'reserved' and receipt['owner_id'].startswith('airun-')
a.output.mkdir(parents=True, exist_ok=False)
root = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root/'src'))
from isaacsim import SimulationApp
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 mobility_fixtures import fixtures, surface_mesh
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 = []
specs = fixtures()
if a.cases:
assert set(a.cases) <= {s['name'] for s in specs}
specs = [s for s in specs if s['name'] in a.cases]
for i, spec in enumerate(specs):
y = i*10.
material = UsdShade.Material.Define(stage, f'/World/Material_{i}')
surface = UsdPhysics.MaterialAPI.Apply(material.GetPrim())
surface.CreateStaticFrictionAttr(.9)
surface.CreateDynamicFrictionAttr(.8)
surface.CreateRestitutionAttr(0)
ground_path = f'/World/Terrain_{i}'
mesh = UsdGeom.Mesh.Define(stage, ground_path)
points, indices = surface_mesh(spec['profile_xz_m'])
mesh.CreatePointsAttr([(x, py+y, z) for x, py, z in points])
mesh.CreateFaceVertexCountsAttr([3]*(len(indices)//3))
mesh.CreateFaceVertexIndicesAttr(indices)
mesh.CreateSubdivisionSchemeAttr(UsdGeom.Tokens.none)
UsdPhysics.CollisionAPI.Apply(mesh.GetPrim())
UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()).Bind(
material, UsdShade.Tokens.weakerThanDescendants, 'physics')
rover = f'/World/Rover_{i}'
create_rover(stage, [0,y,spec['start_z_m']+.3], 0, root_path=rover, model='tracks')
cases.append(dict(spec=spec, root=rover, ground=ground_path, rows=[], stopped=False,
reached=False, target=0., initial_y=y))
SimulationManager.setup_simulation(dt=1/60, device='cpu')
omni.timeline.get_timeline_interface().play()
for _ in range(20): app.update()
for case in cases:
case['drive'] = open_drive(case['root'], model='tracks', contact_filter_paths=[case['ground']])
started, dt = time.monotonic(), 1/60
with (a.output/'motion.jsonl').open('w') as stream:
for frame in range(25*60):
if time.monotonic()-started > 600:
raise TimeoutError('Mobility characterization exceeded 600 seconds')
for case in cases:
target = 0 if frame < 60 or case['stopped'] else case['spec']['target_mps']
case['target'] += np.clip(target-case['target'], -.4*dt, .2*dt)
case['drive'].command(case['target'])
case['drive'].step(dt)
SimulationManager.step(steps=1)
for case in cases:
drive = case['drive']
xyz, q = (v.numpy()[0] for v in drive.body.get_world_poses())
velocity, angular = (v.numpy()[0] for v in drive.body.get_velocities())
up = 1-2*(q[1]**2+q[2]**2)
tilt = math.degrees(math.acos(np.clip(up,-1,1)))
metrics = drive.metrics
row = dict(case=case['spec']['name'], frame=frame, seconds=frame*dt,
monotonic=time.monotonic(), position=xyz.tolist(), quaternion_wxyz=q.tolist(),
velocity=velocity.tolist(), tilt_degrees=tilt,
normal_load_n=metrics['normal_load_n'], belt_mps=metrics['belt_mps'],
motor_force_n=metrics['motor_force_n'], contact_count=metrics['native_contact_count'],
native_contacts=metrics['native_contacts'], supports=metrics['supports'],
contact_geometry_frame=metrics['contact_geometry_frame'],
slip_power_w=metrics['slip_power_w'], commanded_mps=float(case['target']))
if frame >= 60 and not case['stopped']:
if xyz[0] >= case['spec']['goal_x_m']:
case['reached'] = case['stopped'] = True
elif tilt > 65 or xyz[2] < case['spec']['start_z_m']-2 or abs(xyz[1]-case['initial_y']) > 1:
case['stopped'] = True
case['rows'].append(row)
if frame % 6 == 0: stream.write(json.dumps(row,allow_nan=False)+'\n')
if frame % 120 == 0:
(a.output/'progress.json').write_text(json.dumps(dict(frame=frame, wall_seconds=time.monotonic()-started,
cases=[dict(name=c['spec']['name'], x=c['rows'][-1]['position'][0], reached=c['reached']) for c in cases])))
result = []
for case in cases:
rows = case['rows'][60:]
result.append(dict(**case['spec'], reached=case['reached'], final_position=rows[-1]['position'],
maximum_x_m=max(r['position'][0] for r in rows), maximum_tilt_degrees=max(r['tilt_degrees'] for r in rows),
maximum_speed_mps=max(np.linalg.norm(r['velocity']) for r in rows),
final_speed_mps=float(np.linalg.norm(rows[-1]['velocity'])),
maximum_slip_power_w=max(r['slip_power_w'] for r in rows)))
paths = [Path(__file__), *(Path(__file__).with_name(f) for f in
('mobility_fixtures.py','rover_profile.py','tracked_rover.py','track_dynamics.py')),
Path(__file__).parent/'robots/dcd006-v020.json']
report = dict(schema_version='missioncore.tracked-mobility-characterization/v1',
owner_id=receipt['owner_id'], utc=datetime.now(UTC).isoformat(), monotonic=time.monotonic(),
wall_seconds=time.monotonic()-started, simulated_seconds=25, cases=result, robot=ROBOT_DOCUMENT,
source_sha256={p.relative_to(root).as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},
scope='Plant characterization only. No autonomous traversal admission; no physical capability certification.',
sources=['https://www.nist.gov/el/intelligent-systems-division-73500/standard-test-methods-response-robots/ground-robot-tests',
'https://doi.org/10.1186/s40648-016-0058-y'])
(a.output/'report.json').write_text(json.dumps(report,indent=2))
(a.output/'manifest.json').write_text(json.dumps({p.name:hashlib.sha256(p.read_bytes()).hexdigest()
for p in a.output.iterdir() if p.is_file()},indent=2))
print(json.dumps(dict(cases=result, wall_seconds=report['wall_seconds'])),flush=True)
finally:
app.close()