Preserve installed operator workspace before consolidation

Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 09:59:51 +03:00
parent 97614742bb
commit d0e5f90952
368 changed files with 129172 additions and 1856 deletions
@@ -0,0 +1,9 @@
FROM ndc-ai-polygon-cmu:dense-footprint-v1
COPY patch_clearance_preference.py /opt/cmu/patch_clearance_preference.py
COPY missioncore_clearance.hpp /opt/cmu/src/local_planner/src/missioncore_clearance.hpp
WORKDIR /opt/cmu
RUN python3 patch_clearance_preference.py && source /opt/ros/humble/setup.bash \
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="clearance-preference-v2"
@@ -0,0 +1,6 @@
FROM ndc-ai-polygon-cmu:support-v1
COPY missioncore_clearance.hpp /opt/cmu/src/local_planner/src/missioncore_clearance.hpp
WORKDIR /opt/cmu
RUN source /opt/ros/humble/setup.bash && MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="clearance-free-space-utility-v3"
@@ -0,0 +1,8 @@
FROM ndc-ai-polygon-cmu:snapshot-v1
COPY patch_continuous.py /opt/cmu/patch_continuous.py
WORKDIR /opt/cmu
RUN python3 patch_continuous.py && source /opt/ros/humble/setup.bash \
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="independent-odometry-world-path-v1"
@@ -0,0 +1,8 @@
FROM ndc-ai-polygon-cmu:pursuit-v1
COPY patch_dense_footprint.py /opt/cmu/patch_dense_footprint.py
WORKDIR /opt/cmu
RUN python3 patch_dense_footprint.py && source /opt/ros/humble/setup.bash \
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="dense-primitive-footprint-v1"
@@ -0,0 +1,9 @@
FROM ndc-ai-polygon-cmu:connectivity-v2
COPY missioncore_footprint.hpp /opt/cmu/src/local_planner/src/missioncore_footprint.hpp
COPY patch_direction.py /opt/cmu/patch_direction.py
WORKDIR /opt/cmu
RUN python3 patch_direction.py && source /opt/ros/humble/setup.bash \
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="observed-direction-v1"
@@ -0,0 +1,7 @@
FROM ndc-ai-polygon-cmu:clearance-v2
COPY patch_prefix_goal.py /opt/cmu/patch_prefix_goal.py
COPY missioncore_prefix.hpp /opt/cmu/src/local_planner/src/missioncore_prefix.hpp
WORKDIR /opt/cmu
RUN python3 patch_prefix_goal.py && /bin/bash -lc 'source /opt/ros/humble/setup.bash && MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF'
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="prefix-goal-v1"
@@ -0,0 +1,9 @@
FROM ndc-ai-polygon-cmu:continuous-v1
COPY patch_pursuit.py /opt/cmu/patch_pursuit.py
COPY missioncore_pursuit.hpp /opt/cmu/src/local_planner/src/missioncore_pursuit.hpp
WORKDIR /opt/cmu
RUN python3 patch_pursuit.py && source /opt/ros/humble/setup.bash \
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="speed-coupled-pure-pursuit-v1"
@@ -0,0 +1,8 @@
FROM ndc-ai-polygon-cmu:direction-v1
COPY patch_snapshot.py /opt/cmu/patch_snapshot.py
WORKDIR /opt/cmu
RUN python3 patch_snapshot.py && source /opt/ros/humble/setup.bash \
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select terrain_analysis \
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
WORKDIR /adapter
LABEL com.nodedc.navigation-adapter="causal-map-snapshot-v1"
@@ -0,0 +1,8 @@
FROM ndc-ai-polygon-cmu:clearance-v3
COPY support_native.cpp /opt/missioncore/support_native.cpp
RUN g++ -std=c++17 -O3 -shared -fPIC /opt/missioncore/support_native.cpp -o /opt/missioncore/libsupport_surface.so
LABEL com.nodedc.product="mission-core" \
com.nodedc.stack="ai-polygon" \
com.nodedc.role="navigation" \
com.nodedc.managed-by="mission-core-artifact" \
com.nodedc.navigation-support="connected-observed-patches-v2"
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:12835df9ceb377257a7e99ccbbb37636eb67d989e9bf24df8cb530341acf0c3c'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:dense-footprint-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned dense-footprint-v1 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\clearance-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:clearance-v2 -f (Join-Path $PSScriptRoot 'Dockerfile.clearance') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Clearance preference build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:clearance-v2 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_clearance_preference.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:422fdf745e4ba6d5c722422c47a48483a85fe2f952f3a506411f832bded7bba2'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:support-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned support-v1 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\clearance-refinement-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:clearance-v3 -f (Join-Path $PSScriptRoot 'Dockerfile.clearance-refinement') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Support kernel build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:clearance-v3 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'missioncore_clearance.hpp') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -10,8 +10,8 @@ New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:connectivity-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.connectivity') $PSScriptRoot
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:connectivity-v2 -f (Join-Path $PSScriptRoot 'Dockerfile.connectivity') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Terrain connectivity build failed' }
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:connectivity-v1 --format '{{.Id}}'
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:connectivity-v2 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'terrain_connectivity.cpp') -Algorithm SHA256).Hash.ToLower(); installed_at=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:6063ad1e3e4634b3f4f71e445289faf85ba25999b346f70c10b2e2840392271c'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:snapshot-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned snapshot-v1 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\continuous-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:continuous-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.continuous') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Continuous follower build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:continuous-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_continuous.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:f84cbbb110120fbb4a40d18a568b27320d9b2b8bcf930b34a578e46da13cb96b'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:pursuit-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned pursuit-v1 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\dense-footprint-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:dense-footprint-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.dense-footprint') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Dense footprint selector build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:dense-footprint-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_dense_footprint.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,17 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Continue'
$base = 'sha256:a4ba369f9d647c8d69c488d3066a64362277734cbe0533aa3ce7790c6cd63609'
$actual = docker image inspect 'ndc-ai-polygon-cmu:connectivity-v2' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Prepare the pinned connectivity-v2 CMU image first' }
$endpoint = docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\direction-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:direction-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.direction') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Direction policy build failed' }
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:direction-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_direction.py') -Algorithm SHA256).Hash.ToLower(); installed_at=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:c2811450584ebbc61a6b15aa9d8c0663d6e1294fc2355e61ea3de722a5d50b50'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:clearance-v2' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned clearance-v2 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\prefix-goal-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:prefix-goal-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.prefix-goal') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Prefix goal build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:prefix-goal-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_prefix_goal.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:4d680cbec2a78864bceccade5e58b2996a7aa3c51dbaab9c391fdc70abd1c67c'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:continuous-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned continuous-v1 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\pursuit-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:pursuit-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.pursuit') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Pursuit follower build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:pursuit-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_pursuit.py') -Algorithm SHA256).Hash.ToLower(); header_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'missioncore_pursuit.hpp') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,19 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Continue'
$base = 'sha256:aa077bc9177c6b6a8d1bae46c3795e8e38bdd919d324d354d73be7ca5733eaf8'
$actual = docker image inspect 'ndc-ai-polygon-cmu:direction-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned direction-v1 CMU image required' }
$existing = docker image inspect 'ndc-ai-polygon-cmu:snapshot-v1' --format '{{.Id}}' 2>$null
if ($LASTEXITCODE -eq 0) { throw 'Snapshot image exists; inspect its evidence before rebuilding' }
$endpoint = docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\snapshot-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:snapshot-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.snapshot') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Snapshot build failed' }
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:snapshot-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_snapshot.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,18 @@
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
$ErrorActionPreference = 'Stop'
$base = 'sha256:f3f10ee2a594f95d4145635be7feb93b45b1b321c87ae326569db334d094cfc3'
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:prefix-goal-v1' --format '{{.Id}}'
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned prefix-goal-v1 image required' }
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
$config = Join-Path $Root 'state\support-public-build'
New-Item -ItemType Directory -Force $config | Out-Null
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
$env:DOCKER_CONFIG = $config
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:support-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.support') $PSScriptRoot
if ($LASTEXITCODE -ne 0) { throw 'Support kernel build failed' }
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:support-v1 --format '{{.Id}}'
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'support_native.cpp') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
@@ -0,0 +1,255 @@
"""One observed stop-and-orient phase per task goal or declared route segment.
A direction grants no translation, ground or arrival authority. Every pivot
must pass the existing swept-obstacle and support guards on the same sensor
transaction. Completed orientation never overrides a local obstacle detour.
"""
import math
import re
def separate_counter_rotation(speed, yaw_rate, track_centres_y, *, stationary):
"""Autonomy stops before a turn that would reverse one moving track.
A normal forward arc remains continuous. A pivot is only a proposal: the
caller must apply the complete sweep and live observation checks anew.
"""
side_speeds = [speed - yaw_rate * y for y in track_centres_y]
if speed > 0 and min(side_speeds) < 0 < max(side_speeds):
return (
0.0,
yaw_rate if stationary else 0.0,
{
"phase": "pivoting" if stationary else "braking",
"requested_command": [speed, yaw_rate],
"authority": "proposal-requires-swept-obstacle-and-support-admission",
},
)
return speed, yaw_rate, None
def path_alignment_command(path, *, lookahead_m, maximum_yaw_rps):
"""Propose a stationary turn toward the SAME selected local path.
A translation sweep may be blocked beside a front corner while a stationary
pivot is clear. This grants no motion: callers require a stopped body and
independently admit the full pivot with current obstacle and support data.
Do not rotate for a straight blocked path, invent a detour, or reverse.
"""
if len(path) < 2:
return None
point = next((p for p in path if math.hypot(*p[:2]) >= lookahead_m), path[-1])
if not all(math.isfinite(x) for x in point[:2]) or point[0] <= 0:
return None
heading = math.atan2(point[1], point[0])
if abs(heading) <= 0.02:
return None
return 0.0, max(-maximum_yaw_rps, min(maximum_yaw_rps, 2 * heading))
def admit_path_alignment(path, monitor, policy, terrain, pose, contact_height_m,
current_points, *, stationary, reverse, orienting, lookahead_m):
"""A blocked translation can turn first, with its own complete admission.
Ground rejection and body collision both require a different swept region;
neither may authorize the original arc. Reuse the selected path heading,
require a stopped body, and recheck obstacle and support independently.
"""
if not stationary or reverse or orienting:
return None
pivot = path_alignment_command(path, lookahead_m=lookahead_m,
maximum_yaw_rps=policy.partial_yaw_rps)
if pivot is None:
return None
v, w, body_scale = monitor.regulate_command(*pivot, terrain, pose)
if body_scale == 0:
return None
v, w, ground_scale, ground = policy.regulate(
v, w, terrain, pose, contact_height_m, current_points=current_points)
if ground_scale == 0 or ground["status"] != "observed-supported":
return None
return v, w, body_scale, ground_scale, ground, dict(
phase="path-alignment", proposed_command=list(pivot),
authority="stationary-selected-path; independently admitted pivot sweep and support")
def forward_path_command(path, track_centres_y, *, lookahead_m, maximum_speed,
maximum_yaw_rps):
"""Pure-pursuit proposal along the selected path with both tracks forward.
A local follower's rotate-first preference must not be the only proposal
for a driveable bend. Pursue a lookahead on that SAME prefix, limiting
curvature so the inner track keeps at least 10% of the outer track's speed.
This is a steering constraint, not proof the wider arc is clear; its actual
sweep still needs independent admission. Do not extend a short path,
aim directly at the mission goal or grant collision/support admission.
"""
if not track_centres_y or maximum_speed <= 0 or maximum_yaw_rps <= 0:
return None
if len(path) < 2:
return None
candidates = []
for point in path:
x, y = point[:2]
if not all(math.isfinite(n) for n in (x, y)):
return None
if math.hypot(x, y) >= lookahead_m:
candidates.append(point)
if not candidates:
candidates = [path[-1]] # Native paths may be cropped before lookahead.
for point in candidates:
x, y = point[:2]
distance = math.hypot(x, y)
if x <= 0 or distance < min(lookahead_m, max(map(abs, track_centres_y))):
continue
requested_curvature = 2*y/(distance*distance)
minimum_track_ratio = 0.1
radius = max(map(abs, track_centres_y))
if radius <= 0:
return None
limit = (1-minimum_track_ratio)/(1+minimum_track_ratio)/radius
curvature = max(-limit, min(limit, requested_curvature))
speed = min(maximum_speed, maximum_yaw_rps/max(abs(curvature), 1e-12))
yaw_rate = max(-maximum_yaw_rps, min(maximum_yaw_rps, speed*curvature))
return speed, yaw_rate, {
"phase": "forward-path", "lookahead_vehicle_xy": [x, y],
"curvature_per_m": curvature,
"requested_curvature_per_m": requested_curvature,
"minimum_track_ratio": minimum_track_ratio,
"authority": "selected-prefix-proposal; requires live sweep and support",
}
return None
def follower_stopped_short(pose, goal, command, *, arrival_complete, stop_distance):
"""Follower tolerance cannot stand in for measured mission arrival.
Even a fully supported current body can be outside the task region when
its selected destination lies near that region's edge.
"""
return bool(
not arrival_complete
and abs(command[0]) + abs(command[1]) < 1e-5
and math.dist(goal[:2], pose[:2]) <= stop_distance
)
def terminal_path_command(
pose, goal, path, command, *, stop_distance, maximum_speed, command_bounds
):
"""Finish a fresh local path whose follower tolerance precedes body arrival.
This proposes a short final approach only after the caller has admitted
the complete destination. It follows the existing CMU prefix; it never
extends that prefix, certifies support, or changes mission acceptance.
The caller must reassess the actual command through all live sweep gates.
"""
if (
len(path) < 2
or abs(command[0]) + abs(command[1]) > 1e-5
or math.dist(pose[:2], goal[:2]) > 2 * stop_distance
):
return None
x, y = path[-1][:2] # Same-transaction vehicle-yaw frame, not world XY.
distance = math.hypot(x, y)
if not 0 < distance <= 2 * stop_distance or x <= 0:
return None
heading = math.atan2(y, x)
if abs(heading) > 0.3:
return None
yaw = max(-0.15, min(0.15, 2 * heading))
limit = min(maximum_speed, 0.1)
# Use the owning monitor's horizon, not a second copy of its timing limits.
# The upper speed limit makes the bound conservative for the output.
horizon = command_bounds(limit, yaw)["horizon_seconds"]
speed = min(limit, distance / horizon)
return (
speed,
yaw,
{
"phase": "terminal-path",
"path_endpoint_vehicle_xy": [x, y],
"prefix_length_m": distance,
"held_translation_bound_m": speed * horizon,
"authority": "proposal-requires-destination-and-live-sweep-admission",
},
)
def validate_orientation(value):
if value is None:
return None
if (
not isinstance(value, dict)
or set(value) != {"key", "xy"}
or not isinstance(value["key"], str)
or not re.fullmatch(r"[a-zA-Z0-9_-]{1,80}", value["key"])
or not isinstance(value["xy"], list)
or len(value["xy"]) != 2
or any(
isinstance(v, bool) or not isinstance(v, (float, int)) or not math.isfinite(v)
for v in value["xy"]
)
):
raise ValueError("Invalid orientation intent")
return value
class ArrivalApproach:
def __init__(self):
self.turning = self.completed = False
self.previous = self.target = None
def command(self, pose, target, seconds, speed, yaw_rate, *, enabled):
target = validate_orientation(target)
if not enabled or target is None:
self.previous = None
return speed, yaw_rate, {"phase": "local-path"}
if not all(math.isfinite(v) for v in (*pose, seconds, speed, yaw_rate)):
raise ValueError("Non-finite orientation observation")
if self.target != target["key"]:
self.target = target["key"]
self.turning = self.completed = False
self.previous = None
if self.completed:
return speed, yaw_rate, {"phase": "local-path", "target_key": self.target}
if math.dist(pose[:2], target["xy"]) <= 0.4:
self.completed = True
return speed, yaw_rate, {"phase": "body-placement", "target_key": self.target}
observed_speed = None
if self.previous is not None:
position, before = self.previous
dt = seconds - before
if dt < 0:
raise ValueError("Orientation observations must not rewind")
if 0 < dt <= 1:
observed_speed = math.dist(pose[:2], position) / dt
self.previous = (list(pose[:2]), seconds)
x, y, z, w = pose[3:7]
heading = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
bearing = math.atan2(target["xy"][1] - pose[1], target["xy"][0] - pose[0])
error = math.atan2(math.sin(bearing - heading), math.cos(bearing - heading))
self.turning = abs(error) > (0.1 if self.turning else 0.3)
phase = "local-path"
if self.turning:
speed = 0.0
if observed_speed is None or observed_speed > 0.025:
yaw_rate, phase = 0.0, "braking"
else:
yaw_rate = max(-math.radians(20), min(math.radians(20), 2 * error))
phase = "aligning"
else:
self.completed = True
return (
speed,
yaw_rate,
{
"phase": phase,
"target_key": self.target,
"heading_error_radians": error,
"observed_translation_mps": observed_speed,
"proposed_command": [speed, yaw_rate],
"authority": "proposal-requires-swept-obstacle-and-support-admission",
},
)
@@ -0,0 +1,54 @@
"""Bounded spatial refinement of a declared arrival region.
Only proposal coordinates and a cursor survive between observations. Each body
assessment still uses the current terrain, permission, attitude and timestamp.
"""
import math
import numpy as np
class ArrivalPoseSearch:
batch_size = 32
def __init__(self, *, stopping_margin_m=0.0):
if not math.isfinite(stopping_margin_m) or not 0 <= stopping_margin_m < .39:
raise ValueError("Invalid arrival stopping margin")
radius = .39 - stopping_margin_m
axis = np.linspace(-radius, radius, math.ceil(2 * radius / .025) + 1)
offsets = [(float(x), float(y)) for x in axis for y in axis
if math.hypot(x, y) <= radius]
offsets += [(sample_radius * math.cos(angle), sample_radius * math.sin(angle))
for sample_radius in (.1, .2, .3, radius) if sample_radius <= radius
for angle in (0, math.pi/4, -math.pi/4, math.pi/2, -math.pi/2, math.pi)]
self.offsets = list(dict.fromkeys(offsets))
self.ordered = self.offsets
self.target = self.pose = None
self.cursor = 0
def batch(self, pose, target, minimum_translation_m):
key = (*map(float, target), float(minimum_translation_m))
if (self.target != key or self.pose is None
or np.linalg.norm(np.asarray(pose[:3]) - self.pose[:3]) > .025
or abs(float(np.dot(pose[3:], self.pose[3:]))) < math.cos(.025 / 2)):
self.target, self.pose, self.cursor = key, np.asarray(pose).copy(), 0
qx, qy, qz, qw = pose[3:]
yaw = math.atan2(2*(qw*qz+qx*qy), 1-2*(qy*qy+qz*qz))
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
local_target = (np.asarray(target) - np.asarray(pose[:2])) @ axes
def rank(offset):
delta = local_target + offset
return abs(math.atan2(delta[1], delta[0])), float(np.linalg.norm(delta))
# Arrival is a region, not its centre. Prefer a supported placement
# requiring less heading change before considering travel distance.
# Centre-first proposals can cause a needless near-edge pivot.
# This ordering grants no path, support or motion authority.
self.ordered = sorted(self.offsets, key=rank)
if self.cursor >= len(self.offsets):
self.cursor = 0 # Revisit on new observations; no cached admission.
result = self.ordered[self.cursor:self.cursor + self.batch_size]
self.cursor += len(result)
return result
@@ -0,0 +1,44 @@
"""Versioned native support build; preserves the exact qualified CMU predecessor."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
from datetime import UTC, datetime
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
base = 'ndc-ai-polygon-cmu:clearance-v3'
expected = 'sha256:67a7fc163ed27cb029c71a24d6d935562577fe32e20ddb94c4742accdd51a13c'
actual = json.loads(subprocess.check_output(['docker', 'image', 'inspect', base], text=True))[0]['Id']
if actual != expected:
raise RuntimeError('Navigation build predecessor changed')
args.output.mkdir(parents=True, exist_ok=False)
context = args.output / 'context'; context.mkdir()
for src, dest in [('Dockerfile.support', 'Dockerfile'), ('support_native.cpp', 'support_native.cpp')]:
shutil.copyfile(Path(__file__).with_name(src), context / dest)
inputs = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(context.iterdir())}
encoded = json.dumps(dict(base=expected, files=inputs), sort_keys=True).encode()
digest = hashlib.sha256(encoded).hexdigest()
tag = 'ndc-navigation-support:' + digest[:16]
(args.output / 'build-inputs.json').write_bytes(encoded)
with (args.output / 'build.log').open('w') as log:
subprocess.run(['docker', 'build', '--pull=false', '-t', tag, str(context)],
env={**os.environ, 'DOCKER_BUILDKIT': '0'}, stdout=log, stderr=subprocess.STDOUT,
check=True, timeout=180)
identity = json.loads(subprocess.check_output(['docker', 'image', 'inspect', tag], text=True))[0]['Id']
receipt = dict(image=identity, tag=tag, input_sha256=digest,
utc=datetime.now(UTC).isoformat(), predecessor=expected,
runtime_changes='none; isolated image only')
(args.output / 'image.json').write_text(json.dumps(receipt, indent=2))
shutil.rmtree(context)
print(json.dumps(receipt))
if __name__ == '__main__':
main()
@@ -0,0 +1,23 @@
"""Report the gate that actually rejected a command, before unevaluated gates.
No motion permission is created here. In particular, missing visual intent is
not an obstacle observation and must not seed a route exclusion.
"""
def command_failure(*, tilt, orienting, translation_allowed, path_points,
footprint_clear, direction_clear, support_scale,
support_reason, velocity, yaw_rate):
if tilt >= 30:
return "inclination"
if not orienting and not translation_allowed:
return "no-permitted-goal"
if not orienting and path_points <= 1:
return "no-path"
if not direction_clear:
return "direction"
if not footprint_clear:
return "footprint"
if support_scale == 0:
return support_reason
return "controller-hold" if abs(velocity) + abs(yaw_rate) < 1e-5 else "none"
@@ -0,0 +1,106 @@
"""Conservative swept cells of the selected robot's nominal ground contacts.
Contact strips remain separate on straight travel. During a turn we bound each
rotated strip plus the same incomplete-motion/discrepancy bounds as the chassis.
This is flat-ground geometry, not a pressure, bridging or stability model.
"""
import math
import numpy as np
if __package__:
from . import support_native
else:
import support_native
class ContactSupport:
spacing_m = 0.05
angle_step_rad = 0.05
def __init__(self, value, length, width):
if (
value.get("schema_version") != "missioncore.ground-contact/v1"
or value.get("model") != "two-track-bottom-bands"
or [b.get("side") for b in value.get("bands", [])] != ["left", "right"]
):
raise ValueError("Unsupported ground contact geometry")
self.value = value
self.bands = []
for band in value["bands"]:
low, high = np.asarray(band["lower_xy_m"]), np.asarray(band["upper_xy_m"])
if (
low.shape != (2,)
or high.shape != (2,)
or not np.isfinite([low, high]).all()
or np.any(low >= high)
or np.any(np.maximum(np.abs(low), np.abs(high)) > [length / 2, width / 2])
):
raise ValueError("Invalid contact band dimensions")
self.bands.append((low.astype(float), high.astype(float)))
if self.bands[0][0][1] <= self.bands[1][1][1]:
raise ValueError("Track contact bands overlap")
def stationary_samples(self, spacing):
"""Include every band edge/corner without demanding ground in the gap."""
return np.array(
[
[x, y]
for low, high in self.bands
for x in np.linspace(low[0], high[0], math.ceil((high[0] - low[0]) / spacing) + 1)
for y in np.linspace(low[1], high[1], math.ceil((high[1] - low[1]) / spacing) + 1)
]
)
def cells(self, bounds, yaw_rate):
"""All 5 cm cells intersecting the bounded contact sweep, side masks.
Orientation bins are fixed from zero and rounded outwards. A smaller
command removes bins instead of shifting them; the cell lattice is also
fixed. This preserves nesting for same-arc command reduction.
"""
if support_native.LIBRARY is not None:
return support_native.contact_cells(self.bands, bounds, yaw_rate)
low = np.asarray(bounds["centre_lower_xy_m"]) - bounds["discrepancy_xy_m"]
high = np.asarray(bounds["centre_upper_xy_m"]) + bounds["discrepancy_xy_m"]
translation, radius = (low + high) / 2, (high - low) / 2
angle = abs(yaw_rate) * bounds["horizon_seconds"]
count = math.ceil(angle / self.angle_step_rad)
if count > 256:
raise ValueError("Contact sweep exceeds bounded orientation budget")
angles = (
np.sign(yaw_rate) * (np.arange(count) + 0.5) * self.angle_step_rad if count else [0.0]
)
patches = []
# A square cell is enclosed by this radius. Extra angular radius bounds
# every point between the sampled midpoint and either end of its bin.
cell_radius = self.spacing_m / math.sqrt(2)
for side, (a, b) in enumerate(self.bands):
centre, half = (a + b) / 2, (b - a) / 2
reach = np.linalg.norm(np.maximum(np.abs(a), np.abs(b)))
pad = cell_radius + (reach * self.angle_step_rad / 2 if count else 0)
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
axes = np.array([[c, -s], [s, c]])
origin = translation + axes @ centre
normals = np.vstack((np.eye(2), axes.T))
extent = np.abs(normals @ axes) @ half + np.abs(normals) @ radius + pad
patches.append((side, origin, normals, extent))
lower = np.min([p[1] - p[3][:2] for p in patches], axis=0)
upper = np.max([p[1] + p[3][:2] for p in patches], axis=0)
first = np.floor(lower / self.spacing_m).astype(int)
last = np.ceil(upper / self.spacing_m).astype(int)
if np.prod(last - first + 1) > 20000:
raise ValueError("Contact sweep exceeds bounded sample budget")
cells = (
np.array(
[[x, y] for x in range(first[0], last[0] + 1) for y in range(first[1], last[1] + 1)]
)
* self.spacing_m
)
sides = np.zeros((len(cells), 2), dtype=bool)
for side, origin, normals, extent in patches:
sides[:, side] |= np.all(np.abs((cells - origin) @ normals.T) <= extent + 1e-10, axis=1)
keep = np.any(sides, axis=1)
return cells[keep], sides[keep]
@@ -0,0 +1,223 @@
"""Fast control admission, independent of camera inference and map construction.
The native CMU follower supplies proposals from live odometry. Every delivered
proposal is checked against the current observed geometry and contact policy.
Wall-clock observation leases are never renewed by a controller poll.
"""
import math
import copy
import threading
import time
from collections import OrderedDict
import numpy as np
if __package__:
from .arrival_approach import separate_counter_rotation
from .detection_obstacles import DetectionObstacles
else:
from arrival_approach import separate_counter_rotation
from detection_obstacles import DetectionObstacles
class ContinuousControl:
range_deadline = 0.8
pose_deadline = 0.5
semantic_deadline = 2.0
def __init__(self, monitor, support_policy, publish_pose, publish_path, native_command,
clock=time.monotonic, body_top_m=math.inf, native_only=False):
self.monitor, self.support = monitor, support_policy
self.detections = DetectionObstacles(monitor)
self.publish_pose, self.publish_path, self.native_command = (
publish_pose, publish_path, native_command)
self.clock, self.lock = clock, threading.Lock()
self.geometry = None
self.plans = OrderedDict()
self.path_id = None
self.body_top_m = body_top_m
self.range_sequence = None
self.native_only = native_only
def observe(self, value):
age = float(value["geometry_age_seconds"])
if not math.isfinite(age) or age < 0:
raise ValueError("Invalid range capture age")
points = np.asarray(value["points"], dtype=float).reshape(-1, 3).copy()
if not np.isfinite(points).all():
raise ValueError("Non-finite live range")
sequence = value.get("range_sequence")
if sequence is not None:
if (not isinstance(sequence, list) or len(sequence) != 2
or any(type(n) is not int or n < 0 for n in sequence)):
raise ValueError("Invalid range sequence")
sequence = tuple(sequence)
with self.lock:
# Once the direct sensor channel is active, planner transactions
# cannot replace its newer packet or renew its capture lease.
if self.range_sequence is not None and (sequence is None or sequence <= self.range_sequence):
return
self.geometry = (self.clock() - age, points)
self.range_sequence = sequence
def accept(self, value, result, terrain, *, detections=None):
candidates = self.detections.observed(value)
if detections is None:
detections = candidates
else:
detections = np.asarray(detections, dtype=float).reshape(-1, 3).copy()
if not set(map(tuple, detections)) <= set(map(tuple, candidates)):
raise ValueError("Refined detection is not an original associated range return")
record = dict(value=value, result=result, detections=detections,
terrain=np.asarray(terrain, dtype=float).reshape(-1, 4).copy(),
received_at=self.clock())
with self.lock:
self.plans[value["observation_id"]] = record
while len(self.plans) > 4:
self.plans.popitem(last=False)
def snapshot(self):
"""One immutable planning transaction for offline diagnosis, no authority."""
with self.lock:
if not self.plans:
return None
identity, plan = next(reversed(self.plans.items()))
return dict(observation_id=identity, request=copy.deepcopy(plan["value"]),
result=copy.deepcopy(plan["result"]), terrain=plan["terrain"].tolist())
def tick(self, value):
started = self.clock()
pose = np.asarray(value["pose"], dtype=float)
age = float(value["pose_age_seconds"])
perception_age = float(value["perception_age_seconds"])
if (pose.shape != (7,) or not np.isfinite(pose).all()
or abs(np.linalg.norm(pose[3:]) - 1) > 0.01
or not all(math.isfinite(x) and x >= 0 for x in (age, perception_age))
or type(value["enabled"]) is not bool):
raise ValueError("Invalid continuous state")
if "range_observation" in value:
self.observe(value["range_observation"])
# Always feed current state, including while stopped, without waiting
# for terrain_analysis or a model. This publisher is follower-only.
self.publish_pose(pose)
with self.lock:
geometry = self.geometry
plan = self.plans.get(value.get("observation_id"))
def output(v=0.0, w=0.0, reason="waiting", **evidence):
return dict(speed_mps=float(v), yaw_rate_rps=float(w), reason=reason,
processing_ms=(self.clock() - started) * 1000, **evidence)
if not value["enabled"]:
return output(reason="paused")
if age > self.pose_deadline:
return output(reason="stale-pose")
if perception_age > self.semantic_deadline:
return output(reason="stale-perception")
if geometry is None or started - geometry[0] > self.range_deadline:
return output(reason="stale-range")
if len(geometry[1]) < 50:
return output(reason="insufficient-range")
if plan is None or plan["result"].get("status") != "path":
return output(reason="waiting-for-plan")
if started - plan["received_at"] > self.range_deadline:
return output(reason="stale-plan")
request, result = plan["value"], plan["result"]
if (started - plan["received_at"] + request.get("detection_age_seconds", 0)
> self.detections.deadline_seconds):
return output(reason="stale-detection")
if self.path_id != value["observation_id"]:
self.publish_path(result["path"], request["pose"])
self.path_id = value["observation_id"]
native = self.native_command()
if native is None or started - native[0] > 0.25:
return output(reason="waiting-for-controller")
limit = float(request["max_speed_mps"])
reverse = request.get("allow_reverse", False)
stationary = abs(float(value.get("speed_mps", 0))) < 0.02
qx, qy, qz, qw = pose[3:]
if 1 - 2 * (qx*qx + qy*qy) <= math.cos(math.radians(30)):
return output(reason="inclination")
# Newly arrived raw returns can veto a map that has not finished its
# next terrain pass yet. Ground support uses independent first-hit data.
points = geometry[1]
up = np.array([2*(qx*qz + qw*qy), 2*(qy*qz - qw*qx), 1-2*(qx*qx+qy*qy)])
height = (points - pose[:3]) @ up + request["body_contact_height_m"]
raised = (height > self.monitor.max_step + 1e-4) & (height <= self.body_top_m)
hazards = np.column_stack((points[raised], np.ones(int(raised.sum()))))
terrain = np.concatenate((plan["terrain"], hazards))
def admit(command):
speed, angular = map(float, command)
if not all(math.isfinite(x) for x in (speed, angular)):
return output(reason="invalid-proposal")
speed = max(-limit, min(limit, speed))
angular = max(-0.8, min(0.8, angular))
if not self.native_only and not reverse and self.monitor.contacts is not None:
speed, angular, _ = separate_counter_rotation(speed, angular,
[(low[1]+high[1])/2 for low, high in self.monitor.contacts.bands],
stationary=stationary)
if abs(speed) < 1e-8 and abs(angular) > 1e-8:
angular = max(-self.support.partial_yaw_rps,
min(self.support.partial_yaw_rps, angular)) if stationary else 0.0
if (reverse and (speed > 0 or abs(angular) > 0.15)) or (not reverse and speed < 0):
return output(reason="direction")
speed, angular, obstacle_scale = self.monitor.regulate_command(speed, angular, terrain, pose)
if obstacle_scale == 0:
return output(reason="obstacle")
speed, angular, support_scale, support = self.support.regulate(
speed, angular, terrain, pose, request["body_contact_height_m"],
current_points=points,
)
evidence = dict(support_policy=support["policy"]["reason"],
support_reasons=support["support_reasons"],
fresh_context=support["policy"]["fresh_context"])
if support_scale == 0:
return output(reason=support["policy"]["reason"], **evidence)
speed, angular, detection_scale = self.detections.regulate(
speed, angular, plan["detections"], pose)
evidence["detection_command_scale"] = detection_scale
if detection_scale == 0:
return output(reason="detected-object-sweep", **evidence)
return output(speed, angular, "none", **evidence)
if self.native_only:
# Nav2 owns the proposal. No CMU fallback, arrival override or
# alternative local pursuit may become a competing controller.
response = admit(native[1:])
response.update(command_source="nav2", observation_id=value["observation_id"],
native_command=list(native[1:]),
processing_ms=(self.clock()-started)*1000)
return response
planned = [result["speed_mps"], result["yaw_rate_rps"]]
approach = result.get("diagnostic", {}).get("arrival_approach", {})
phase = approach.get("phase")
terminal = result.get("diagnostic", {}).get("terminal_approach")
local_turn = result.get("diagnostic", {}).get("local_turn") or {}
if phase == "path-alignment" and not stationary:
return output(reason="path-alignment-braking")
# A short, destination-admitted terminal prefix may lie inside the
# native follower's stop tolerance. Its valid zero command must not
# suppress the terminal proposal. It retains the plan's bounded lease
# and traverses exactly the same current-pose/range guards below.
proposal = planned if (terminal or local_turn.get("phase") == "forward-path"
or phase in {"braking", "aligning", "path-alignment"}) else native[1:]
response = admit(proposal)
source = ("local-path" if local_turn.get("phase") == "forward-path" else "arrival") \
if proposal is planned else "follower"
if response["reason"] != "none" and tuple(proposal) != tuple(planned):
# A fresh path proposal and the live follower can disagree on
# curvature. Test the planner's original command at the CURRENT
# pose and ranges before declaring deadlock. This is no admission
# shortcut: both candidates traverse exactly the same guards.
fallback = admit(planned)
if fallback["reason"] == "none":
fallback["rejected_follower"] = response
response, source = fallback, "guarded-plan"
response.update(range_age_ms=(started-geometry[0])*1000,
pose_age_ms=age*1000, perception_age_ms=perception_age*1000,
native_command=list(native[1:]), command_source=source,
observation_id=value["observation_id"],
processing_ms=(self.clock()-started)*1000)
return response
@@ -0,0 +1,70 @@
"""Observed detector hazards enter search and command admission separately.
Inspired by the obstacle-layer / collision-monitor separation in Nav2. Boxes
alone never create metric obstacles. Source indices bind each hazard to this
range transaction. Search costs mark existing measured voxels; the independent
swept-body guard tests the exact associated returns at the current pose.
This is a simulation candidate, not a certified human-separation controller.
"""
import copy
import math
import numpy as np
class DetectionObstacles:
deadline_seconds = 2.0
# Additional reserve for detector-associated objects. Separate from the
# ordinary 5 cm rigid-body margin, terrain capability and road permissions.
clearance_m = 0.35
voxel_m = 0.12
def __init__(self, monitor):
self.monitor = copy.copy(monitor)
self.monitor.clearance_m = max(monitor.clearance_m, self.clearance_m)
self.cost = monitor.max_step + 1.0
@staticmethod
def observed(value):
points = np.asarray(value["points"], dtype=float).reshape(-1, 3)
indices = value.get("detection_point_indices", [])
if (not isinstance(indices, list) or len(indices) > len(points)
or len(indices) != len(set(indices))
or any(type(i) is not int or not 0 <= i < len(points) for i in indices)
or not np.isfinite(points).all()):
raise ValueError("Invalid detector range association")
age = float(value.get("detection_age_seconds", 0))
if not math.isfinite(age) or age < 0:
raise ValueError("Invalid detector capture age")
return points[indices].copy()
def overlay(self, terrain, detected):
if not len(detected):
return terrain
cells = set(map(tuple, np.floor(detected / self.voxel_m).astype(np.int64)))
keys = np.floor(terrain[:, :3] / self.voxel_m).astype(np.int64)
marked = np.fromiter((tuple(k) in cells for k in keys), bool, len(keys))
result = terrain.copy()
result[marked, 3] = np.maximum(result[marked, 3], self.cost)
return result
@staticmethod
def without_ground(detected, permitted_terrain):
"""Remove only positively permitted PCL ground in this exact scan.
No voxel-neighbour inference: segmentation preserves original return
indices; unknown and unmatched candidates keep their object reserve.
Raw range and CMU geometric costs remain untouched.
"""
detected = np.asarray(detected, dtype=float).reshape(-1, 3)
ground = np.asarray(permitted_terrain, dtype=np.float32).reshape(-1, 3)
if not np.isfinite(detected).all() or not np.isfinite(ground).all():
raise ValueError("Non-finite detection ground observation")
known = set(map(tuple, ground))
keep = np.fromiter((tuple(p) not in known for p in detected.astype(np.float32)), bool, len(detected))
return detected[keep].copy()
def regulate(self, speed, angular, detected, pose):
# These are the original XYZ returns, not filled voxels or box centres.
terrain = np.column_stack((detected, np.full(len(detected), self.cost)))
return self.monitor.regulate_command(speed, angular, terrain, pose)
+545 -86
View File
@@ -1,7 +1,7 @@
"""Metre-square swept-body check on CMU's observed terrain and chosen path.
"""Selected robot swept-body check on CMU's observed terrain and chosen path.
CMU's circular path table proposes paths. This final adapter check preserves
the actual square chassis, including the initial turn, without widening it to
the actual rectangular chassis, including the initial turn, without widening it to
its circumscribed circle for straight travel. No scene geometry enters here.
"""
@@ -9,99 +9,558 @@ import math
import numpy as np
MAX_STEP_M = 0.10
if __package__:
from .contact_support import ContactSupport
from .support_surface import SupportSurface
else:
from contact_support import ContactSupport
from support_surface import SupportSurface
FRAME_DEADLINE_SECONDS = 0.8
def _obstacles(terrain, pose):
terrain = np.asarray(terrain, dtype=float)
obstacles = terrain[terrain[:, 3] > MAX_STEP_M + 1e-4, :2] - np.asarray(pose[:2])
x, y, z, w = pose[3:]
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
return obstacles @ np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
def _clearances(obstacles):
return np.maximum(np.abs(obstacles[:, 0]) - 0.5, np.abs(obstacles[:, 1]) - 0.5)
def _clear(obstacles, position, angle):
delta = obstacles - position
c, s = math.cos(angle), math.sin(angle)
along = delta[:, 0] * c + delta[:, 1] * s
across = -delta[:, 0] * s + delta[:, 1] * c
initial = _clearances(obstacles)
if np.any(initial <= 0):
return False # Never excuse an overlap of the actual metre-square body.
clearance = np.maximum(np.abs(along) - 0.5, np.abs(across) - 0.5)
# An observed point may already be inside the 5 cm reserve behind the body.
# Permit only motion that never decreases that initial clearance. This
# cannot authorize moving toward it, reversing into it or corner penetration.
return bool(np.all(clearance + 1e-6 >= np.minimum(initial, 0.05)))
def command_footprint_clear(speed, yaw_rate, terrain, pose):
"""Collision monitor over deadman latency plus a conservative braking arc.
CMU replans the route continuously. A later blocked corner must not prevent
safe progress on its prefix; this checks the command that can actually be
applied before the source-frame deadline, plus braking and 0.5 s reserve.
"""
obstacles = _obstacles(terrain, pose)
horizon = FRAME_DEADLINE_SECONDS + 0.5 + abs(speed) / 0.4 + abs(yaw_rate) / 1.6
for t in np.arange(0, horizon + 0.025, 0.025):
angle = yaw_rate * t
position = (
np.array([speed * math.sin(angle) / yaw_rate, speed * (1 - math.cos(angle)) / yaw_rate])
if abs(yaw_rate) > 1e-6
else np.array([speed * t, 0])
class Footprint:
def __init__(self, geometry, deceleration=0.4, *, clearance_m=0.05):
self.half_length = geometry["length_m"] / 2
self.half_width = geometry["width_m"] / 2
# Mounted bodies affect collision clearance; tracks still define support.
self.collision_half_length = geometry.get("collision_length_m", geometry["length_m"]) / 2
self.collision_half_width = geometry.get("collision_width_m", geometry["width_m"]) / 2
if (not all(math.isfinite(v) for v in
(self.collision_half_length, self.collision_half_width))
or self.collision_half_length < self.half_length
or self.collision_half_width < self.half_width):
raise ValueError("Collision projection cannot shrink the chassis")
self.max_step = geometry["max_step_m"]
self.max_slope = math.tan(math.radians(geometry["max_slope_degrees"]))
self.deceleration = deceleration
self.clearance_m = float(clearance_m)
if not math.isfinite(self.clearance_m) or self.clearance_m < 0.05:
raise ValueError("Invalid obstacle clearance")
if min(self.half_length, self.half_width, self.max_step, deceleration) <= 0:
raise ValueError("Invalid footprint geometry")
self.contacts = (
ContactSupport(geometry["ground_contact"], geometry["length_m"], geometry["width_m"])
if "ground_contact" in geometry
else None
)
if not _clear(obstacles, position, angle):
def classify_contacts(self, surface, offsets):
if self.contacts is None:
return surface.classify(offsets)
width = min(high[1]-low[1] for low, high in self.contacts.bands)
return surface.classify_contacts(offsets, width)
def _obstacles(self, terrain, pose):
terrain = np.asarray(terrain, dtype=float)
obstacles = terrain[terrain[:, 3] > self.max_step + 1e-4, :2] - np.asarray(pose[:2])
x, y, z, w = pose[3:]
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
return obstacles @ np.array(
[[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]
)
def _clearances(self, obstacles):
return np.maximum(
np.abs(obstacles[:, 0]) - self.collision_half_length,
np.abs(obstacles[:, 1]) - self.collision_half_width
)
def _clear(self, obstacles, position, angle):
delta = obstacles - position
c, s = math.cos(angle), math.sin(angle)
along = delta[:, 0] * c + delta[:, 1] * s
across = -delta[:, 0] * s + delta[:, 1] * c
initial = self._clearances(obstacles)
if np.any(initial <= 0):
return False # Never excuse an overlap of the actual robot body.
clearance = np.maximum(np.abs(along) - self.collision_half_length,
np.abs(across) - self.collision_half_width)
# An observed point may already be inside the 5 cm reserve behind the body.
# Permit only motion that never decreases that initial clearance. This
# cannot authorize moving toward it, reversing into it or corner penetration.
return bool(np.all(clearance + 1e-6 >= np.minimum(initial, self.clearance_m)))
def assess_pose(self, terrain, pose, contact_height_m, *, support_terrain=None):
"""Certify a stationary body using observed support, never empty space.
The 10 cm lattice includes every contact edge and corner for v2, or
every body edge and corner for legacy v1. Each point
must lie inside a local observed ground patch (15 cm radius), with a
bounded plane slope/residual. Nearest returns alone cannot extrapolate
support past a ledge. This is sampled geometric support, not load or
soil-bearing-capacity estimation, and does not authorize a path to it.
"""
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
pose = np.asarray(pose, dtype=float)
if not np.isfinite(terrain).all() or pose.shape != (7,) or not np.isfinite(pose).all():
raise ValueError("Invalid body assessment observation")
qx, qy, qz, qw = pose[3:]
yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
spacing, radius = 0.1, 0.15
grid = (
self.contacts.stationary_samples(spacing)
if self.contacts is not None
else np.array(
[
[x, y]
for x in np.linspace(
-self.half_length,
self.half_length,
math.ceil(2 * self.half_length / spacing) + 1,
)
for y in np.linspace(
-self.half_width,
self.half_width,
math.ceil(2 * self.half_width / spacing) + 1,
)
]
)
) @ axes.T
support = (
terrain
if support_terrain is None
else np.asarray(support_terrain, dtype=float).reshape(-1, 4)
)
if not np.isfinite(support).all():
raise ValueError("Invalid support observation")
surface = SupportSurface(
support, pose, contact_height_m, self.max_step, self.max_slope,
anchor_radius_m=math.hypot(self.half_length, self.half_width)
)
states, reasons = self.classify_contacts(surface, grid)
supported = int(np.count_nonzero(states == "observed-supported"))
collision_free = self._clear(self._obstacles(terrain, pose), np.zeros(2), 0)
return dict(
schema_version="missioncore.body-clearance/v2"
if self.contacts is not None
else "missioncore.body-clearance/v1",
collision_free=collision_free,
support_known=supported == len(grid),
admitted=collision_free and supported == len(grid),
support_samples=len(grid),
supported_samples=supported,
support_spacing_m=spacing,
support_radius_m=radius,
support_reasons=reasons,
**({"ground_contact": self.contacts.value} if self.contacts is not None else {}),
)
def find_arrival_pose(
self,
terrain,
pose,
target_xy,
contact_height_m,
*,
support_terrain=None,
minimum_translation_m=0.0,
refinement=None,
):
"""Find an observed pose inside the existing 0.4 m task region.
Keep the measured heading; do not assume room for a turn. The bounded
search proposes a destination only. CMU must plan it on a new sensor
transaction, and the command sweep retains its independent veto.
"""
if not math.isfinite(minimum_translation_m) or minimum_translation_m < 0:
raise ValueError("Invalid arrival translation minimum")
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
pose = np.asarray(pose, dtype=float)
qx, qy, qz, qw = pose[3:]
up = np.array(
[2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx * qx + qy * qy)]
)
if up[2] <= 0:
return None
yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
# Sample centre, then forward and lateral options. The 1 cm inset
# belongs to the proposal; the mission's admission radius stays 0.4 m.
offsets = [(0, 0)] + [
(radius * math.cos(yaw + angle), radius * math.sin(yaw + angle))
for radius in (0.1, 0.2, 0.3, 0.39)
for angle in (0, math.pi / 4, -math.pi / 4, math.pi / 2, -math.pi / 2, math.pi)
]
if refinement is not None:
# The radial coarse search can miss a narrow but fully supported
# placement. Refine at the existing 2.5 cm sweep resolution without
# monopolizing a planning transaction. Never retain body receipts.
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
offsets = [axes @ offset for offset in refinement.batch(
pose, target_xy, minimum_translation_m)]
for offset in offsets:
candidate = pose.copy()
candidate[:2] = np.asarray(target_xy) + offset
if np.linalg.norm(candidate[:2] - pose[:2]) <= minimum_translation_m:
continue
candidate[2] -= np.dot(up[:2], candidate[:2] - pose[:2]) / up[2]
# Cheap identical collision veto before fitting contact support.
if not self._clear(self._obstacles(terrain, candidate), np.zeros(2), 0):
continue
if self.assess_pose(
terrain, candidate, contact_height_m, support_terrain=support_terrain
)["admitted"]:
return candidate.tolist()
return None
def find_observed_approach(
self, terrain, pose, target_xy, contact_height_m, *, support_terrain, minimum_translation_m
):
"""Propose a full supported body placement before an unseen destination.
Only measured, positively classified support may supply this bounded
receding horizon. This is not an arrival, a path, or motion permission;
the local planner and swept command gates remain mandatory.
"""
pose = np.asarray(pose, dtype=float)
delta = np.asarray(target_xy, dtype=float) - pose[:2]
distance = np.linalg.norm(delta)
if distance <= 0.4 or support_terrain is None or len(support_terrain) == 0:
return None
if not math.isfinite(minimum_translation_m) or minimum_translation_m <= 0:
raise ValueError("Invalid approach translation minimum")
qx, qy, qz, qw = pose[3:]
up = np.array(
[2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx * qx + qy * qy)]
)
if up[2] <= 0:
return None
limit = min(distance - 0.41, 2 * max(self.half_length, self.half_width))
# Stop before the unchanged task region. A candidate is never accepted
# merely because the current body is supported; assess its whole body.
for travel in np.arange(limit, minimum_translation_m, -0.1):
candidate = pose.copy()
offset = delta * travel / distance
candidate[:2] += offset
candidate[2] -= np.dot(up[:2], offset) / up[2]
if self.assess_pose(
terrain, candidate, contact_height_m, support_terrain=support_terrain
)["admitted"]:
return candidate.tolist()
return None
def command_bounds(self, speed, yaw_rate):
"""Bound a held command, allowing incomplete translation and turning.
The body need not follow an ideal differential-drive arc: each response
can range from zero to the requested rate. Bound its centre by integrating
component extrema over that heading sector, then add the rotating body's
rectangular projections. Straight travel retains rectangular dimensions.
The additional directional discrepancy is an empirical simulation margin,
calibrated on the DCD-006 flat-ground matrix (100/130 kg, 0.1–0.3 m/s,
friction 0.35/0.8). It is not a physical guarantee, a ground-support proof,
or qualification of every speed/load accepted by the settings editor.
"""
if not math.isfinite(speed) or not math.isfinite(yaw_rate):
raise ValueError("Non-finite motion command")
horizon = (
FRAME_DEADLINE_SECONDS + 0.5 + abs(speed) / self.deceleration + abs(yaw_rate) / 1.6
)
angle = abs(yaw_rate) * horizon
def extent(along, across):
if angle >= math.atan2(across, along):
return math.hypot(along, across)
return along * math.cos(angle) + across * math.sin(angle)
cosine_min = math.cos(min(angle, math.pi))
sine_max = math.sin(min(angle, math.pi / 2))
sine_min = 0 if angle <= math.pi else math.sin(min(angle, 1.5 * math.pi))
if yaw_rate < 0:
sine_min, sine_max = -sine_max, -sine_min
travel = speed * horizon
x_range = sorted((travel * min(0, cosine_min), travel))
y_range = sorted((travel * min(0, sine_min), travel * max(0, sine_max)))
half = np.array(
[extent(self.collision_half_length, self.collision_half_width), extent(self.collision_half_width, self.collision_half_length)]
)
lower = np.array([x_range[0], y_range[0]]) - half
upper = np.array([x_range[1], y_range[1]]) + half
discrepancy = horizon * (np.array([0.01, 0.03]) + 0.15 * abs(yaw_rate))
return dict(
horizon_seconds=horizon,
centre_lower_xy_m=[x_range[0], y_range[0]],
centre_upper_xy_m=[x_range[1], y_range[1]],
lower_xy_m=lower.tolist(),
upper_xy_m=upper.tolist(),
discrepancy_xy_m=discrepancy.tolist(),
)
def command_footprint_clear(self, speed, yaw_rate, terrain, pose):
"""Veto observed obstacles in the command's bounded swept body.
Empty observations do not certify terrain support. The independent
planner, unknown-space policy and stationary arrival checks retain that
responsibility. A zero return from regulation always means stop; it is
never a certificate that an already unsafe pose has become safe.
"""
bounds = self.command_bounds(speed, yaw_rate)
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
pose = np.asarray(pose, dtype=float)
if pose.shape != (7,) or not np.isfinite(pose).all() or not np.isfinite(terrain).all():
raise ValueError("Invalid swept-body observation")
obstacles = self._obstacles(terrain, pose)
initial = self._clearances(obstacles)
if np.any(initial <= 0):
return False
return True
lower, upper = np.array(bounds["lower_xy_m"]), np.array(bounds["upper_xy_m"])
error = np.array(bounds["discrepancy_xy_m"])
clearance = np.maximum(lower - obstacles, obstacles - upper).max(axis=1)
hard_clearance = np.maximum(lower - error - obstacles, obstacles - upper - error).max(
axis=1
)
# Keep the pre-existing reserve exception, but never excuse penetration
# of the body discrepancy envelope, even when departing an obstacle.
suspects = (clearance + 1e-6 < np.minimum(initial, self.clearance_m)) | (hard_clearance <= 0)
if not np.any(suspects):
return True
return self._rotating_envelope_clear(
obstacles[suspects], initial[suspects], bounds, yaw_rate)
def _rotating_envelope_clear(self, obstacles, initial, bounds, yaw_rate):
"""Refine the broad AABB without shrinking any motion uncertainty.
def regulate_command(speed, yaw_rate, terrain, pose):
"""Reduce speed along CMU's same arc when its full-speed stop is unsafe.
AABB corners combine body extrema attained at different headings and
can falsely forbid a pivot AWAY from an obstacle beside the front.
Retain the entire uncertain translation rectangle at every orientation.
Test its Minkowski sum with the oriented body on all four separating
axes. Each angular interval is enclosed by a corner-displacement disk;
this is an outer bound between samples, not a collision sampling gap.
The same reserve, latency, braking and discrepancy remain mandatory.
"""
angle = max(-2 * math.pi, min(2 * math.pi, yaw_rate * bounds["horizon_seconds"]))
if abs(angle) < 1e-12:
return False # Straight AABB is already exact.
low, high = np.array(bounds["centre_lower_xy_m"]), np.array(bounds["centre_upper_xy_m"])
centre, half = (low + high) / 2, (high - low) / 2
error = np.array(bounds["discrepancy_xy_m"])
count = max(1, math.ceil(abs(angle) / 0.025))
step = angle / count
radius = math.hypot(self.collision_half_length, self.collision_half_width)
delta = obstacles - centre
reserve = np.minimum(initial, self.clearance_m)
intervals = [(index * step, (index + 1) * step, 0) for index in range(count)]
while intervals:
start, end, depth = intervals.pop()
theta = (start + end) / 2
angular_error = 2 * radius * math.sin(abs(end - start) / 4)
c, s = math.cos(theta), math.sin(theta)
abs_c, abs_s = abs(c), abs(s)
# Axes of the axis-aligned centre box and of the rotated chassis
# are all edge normals of their Minkowski sum (a zonotope).
projections = np.column_stack((np.abs(delta),
np.abs(delta[:,0]*c + delta[:,1]*s),
np.abs(-delta[:,0]*s + delta[:,1]*c)))
extent = np.array([
half[0] + self.collision_half_length*abs_c + self.collision_half_width*abs_s,
half[1] + self.collision_half_length*abs_s + self.collision_half_width*abs_c,
self.collision_half_length + half[0]*abs_c + half[1]*abs_s,
self.collision_half_width + half[0]*abs_s + half[1]*abs_c,
])
separation = projections - extent
uncertainty = np.array([error[0], error[1],
error[0]*abs_c + error[1]*abs_s, error[0]*abs_s + error[1]*abs_c])
# A midpoint collision is an actual counterexample. Otherwise an
# inconclusive outer bound needs refinement, not a permanent veto:
# a coarse angular disk can consume a genuinely clear few mm at a
# corner and strand the same nominal path on every observation.
if np.any(separation.max(axis=1) + 1e-6 < reserve):
return False
if np.any((separation - uncertainty).max(axis=1) <= 0):
return False
bounded = separation - angular_error
if (np.any(bounded.max(axis=1) + 1e-6 < reserve)
or np.any((bounded - uncertainty).max(axis=1) <= 0)):
if depth >= 10:
return False # Unresolved intervals never grant motion.
intervals.extend(((start, theta, depth + 1), (theta, end, depth + 1)))
return True
Scaling both components preserves curvature. The shortened stopping envelope
is a prefix of the original arc, so search for its largest admitted scale.
Never choose another turn/direction, ignore a hazard or creep arbitrarily.
"""
if command_footprint_clear(speed, yaw_rate, terrain, pose):
return speed, yaw_rate, 1.0
low, high = 0.2, 1.0
if not command_footprint_clear(speed * low, yaw_rate * low, terrain, pose):
return 0.0, 0.0, 0.0
for _ in range(7):
middle = (low + high) / 2
if command_footprint_clear(speed * middle, yaw_rate * middle, terrain, pose):
low = middle
def assess_command_support(
self, speed, yaw_rate, terrain, pose, contact_height_m, *, surface=None
):
"""Check newly entered area, without demanding sight through the body.
Legacy inputs use the full-body lattice; v2 uses selected contact bands.
Each fixed lattice rounds outward from its envelope. Its samples
are nested when command scale decreases; reducing speed cannot skip a
failed sample by shifting a grid. The currently occupied body is excluded
from this future-ground test, not painted as observed terrain. Known
obstacles retain their independent full-body veto. A stop is always
available and does not certify that the existing pose is safe.
"""
bounds = self.command_bounds(speed, yaw_rate)
lower = np.array(bounds["lower_xy_m"]) - bounds["discrepancy_xy_m"]
upper = np.array(bounds["upper_xy_m"]) + bounds["discrepancy_xy_m"]
if self.contacts is not None:
spacing = self.contacts.spacing_m
local, sides = self.contacts.cells(bounds, yaw_rate)
else:
high = middle
return speed * low, yaw_rate * low, low
spacing = 0.1
low, high = np.floor(lower / spacing).astype(int), np.ceil(upper / spacing).astype(int)
if np.prod(high - low + 1) > 20000:
raise ValueError("Support envelope exceeds bounded sample budget")
local = (
np.array(
[[x, y] for x in range(low[0], high[0] + 1) for y in range(low[1], high[1] + 1)]
)
* spacing
)
pose = np.asarray(pose, dtype=float)
if pose.shape != (7,) or not np.isfinite(pose).all():
raise ValueError("Invalid support pose")
x, y, z, w = pose[3:]
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
offsets = local @ axes.T
current = (np.abs(local[:, 0]) <= self.half_length) & (
np.abs(local[:, 1]) <= self.half_width
)
moving = abs(speed) + abs(yaw_rate) > 1e-8
required = ~current if moving else np.zeros(len(local), bool)
if surface is None:
surface = SupportSurface(terrain, pose, contact_height_m, self.max_step, self.max_slope,
anchor_radius_m=math.hypot(self.half_length, self.half_width))
states, reasons = self.classify_contacts(surface, offsets[required])
supported = int(np.count_nonzero(states == "observed-supported"))
unknown = int(np.count_nonzero(states == "unknown"))
unsafe = int(np.count_nonzero(states == "observed-unsafe"))
missing = offsets[required][states != "observed-supported"] + pose[:2]
return dict(
schema_version="missioncore.swept-support/v2"
if self.contacts is not None
else "missioncore.swept-support/v1",
admitted=supported == len(states),
status="hold"
if not moving
else "current-footprint-only"
if not len(states)
else "observed-unsafe"
if unsafe
else "unknown"
if unknown
else "observed-supported",
support_samples=len(states),
supported_samples=supported,
unknown_samples=unknown,
unsafe_samples=unsafe,
current_body_excluded_samples=int(current.sum()),
scope="newly-entered-area; current body occupancy is not a ground observation",
support_spacing_m=spacing,
support_radius_m=SupportSurface.radius_m,
support_reasons=reasons,
bounds=bounds,
roughness_obstacles_xyz=list(surface.raised_obstacles.values()),
support_obstacle_samples=surface.hazard_samples(
offsets[required][states == "observed-unsafe"]),
unsupported_xy=missing[:12].tolist(),
**(
{
"ground_contact": self.contacts.value,
"per_side": {
name: {
"support_samples": int(sides[required, side].sum()),
"unknown_samples": int(
np.count_nonzero((states == "unknown") & sides[required, side])
),
"unsafe_samples": int(
np.count_nonzero(
(states == "observed-unsafe") & sides[required, side]
)
),
}
for side, name in enumerate(("left", "right"))
},
}
if self.contacts is not None
else {}
),
)
def regulate_supported_command(self, speed, yaw_rate, terrain, pose, contact_height_m):
"""The same requested arc must pass obstacle and new-ground checks."""
surface = SupportSurface(terrain, pose, contact_height_m, self.max_step, self.max_slope,
anchor_radius_m=math.hypot(self.half_length, self.half_width))
def swept_footprint_clear(path, terrain, pose):
path = np.asarray(path, dtype=float)[:, :2]
terrain = np.asarray(terrain, dtype=float)
if len(path) < 2 or terrain.ndim != 2 or terrain.shape[1] != 4:
return False
obstacles = _obstacles(terrain, pose)
def assess(scale):
v, w = speed * scale, yaw_rate * scale
ground = self.assess_command_support(
v, w, terrain, pose, contact_height_m, surface=surface
)
return self.command_footprint_clear(v, w, terrain, pose) and ground["admitted"], ground
previous_angle = 0.0
for start, end in zip(path[:-1], path[1:], strict=True):
delta = end - start
length = np.linalg.norm(delta)
if length < 1e-6:
continue
angle = math.atan2(delta[1], delta[0])
turn = math.atan2(math.sin(angle - previous_angle), math.cos(angle - previous_angle))
for fraction in np.linspace(0, 1, max(2, math.ceil(abs(turn) / 0.035) + 1)):
if not _clear(obstacles, start, previous_angle + fraction * turn):
return False
for fraction in np.linspace(0, 1, max(2, math.ceil(length / 0.025) + 1)):
if not _clear(obstacles, start + fraction * delta, angle):
return False
previous_angle = angle
return True
clear, support = assess(1.0)
if clear:
return speed, yaw_rate, 1.0, support
low, high = self.minimum_command_scale(speed, yaw_rate), 1.0
clear, support = assess(low)
if not clear:
return 0.0, 0.0, 0.0, support
for _ in range(7):
middle = (low + high) / 2
clear, candidate = assess(middle)
if clear:
low, support = middle, candidate
else:
high = middle
return speed * low, yaw_rate * low, low, support
def regulate_command(self, speed, yaw_rate, terrain, pose):
"""Reduce speed along CMU's same arc when its full-speed stop is unsafe.
Scaling both components preserves requested curvature. The sector bounds
and discrepancy shrink monotonically, so find the largest admitted scale.
Never choose another turn/direction, ignore a hazard or creep arbitrarily.
"""
if self.command_footprint_clear(speed, yaw_rate, terrain, pose):
return speed, yaw_rate, 1.0
low, high = self.minimum_command_scale(speed, yaw_rate), 1.0
if not self.command_footprint_clear(speed * low, yaw_rate * low, terrain, pose):
return 0.0, 0.0, 0.0
for _ in range(7):
middle = (low + high) / 2
if self.command_footprint_clear(speed * middle, yaw_rate * middle, terrain, pose):
low = middle
else:
high = middle
return speed * low, yaw_rate * low, low
@staticmethod
def minimum_command_scale(speed, yaw_rate):
"""Bound arbitrarily slow creep in physical units, not a setpoint ratio.
The existing 0.1 commands admitted regulation down to 0.02 m/s or
rad/s. Keep that simulation floor for larger setpoints too: raising
the operator's maximum must not remove an already feasible slow arc.
Smaller original proposals (e.g. acceleration ramps) stay unchanged.
This is an operational floor, not a motor/traction qualification.
"""
magnitude = abs(speed) if abs(speed) > 1e-8 else abs(yaw_rate)
return min(1.0, 0.02 / max(magnitude, 1e-12))
def swept_footprint_clear(self, path, terrain, pose):
path = np.asarray(path, dtype=float)[:, :2]
terrain = np.asarray(terrain, dtype=float)
if len(path) < 2 or terrain.ndim != 2 or terrain.shape[1] != 4:
return False
obstacles = self._obstacles(terrain, pose)
previous_angle = 0.0
for start, end in zip(path[:-1], path[1:], strict=True):
delta = end - start
length = np.linalg.norm(delta)
if length < 1e-6:
continue
angle = math.atan2(delta[1], delta[0])
turn = math.atan2(math.sin(angle - previous_angle), math.cos(angle - previous_angle))
for fraction in np.linspace(0, 1, max(2, math.ceil(abs(turn) / 0.035) + 1)):
if not self._clear(obstacles, start, previous_angle + fraction * turn):
return False
for fraction in np.linspace(0, 1, max(2, math.ceil(length / 0.025) + 1)):
if not self._clear(obstacles, start + fraction * delta, angle):
return False
previous_angle = angle
return True
@@ -0,0 +1,87 @@
"""Select a nearby forward arc when the chosen path's first command is blocked.
CMU still owns the path. Like a trajectory-sampling controller, this adapter
checks several velocities against that path and the independent body/support
constraints. No new target, map permission or unseen ground is created here.
"""
import math
import numpy as np
if __package__:
from .arrival_approach import forward_path_command
else:
from arrival_approach import forward_path_command
def follows_prefix(command, path, monitor, tolerance):
"""The entire nominal stop trajectory stays near the existing local path."""
points = np.asarray(path, dtype=float)[:, :2]
if len(points) < 2 or not np.isfinite(points).all():
return False
a, delta = points[:-1], np.diff(points, axis=0)
length = np.linalg.norm(delta, axis=1)
keep = length > 1e-8
if not keep.any():
return False
a, delta, length = a[keep], delta[keep], length[keep]
starts = np.r_[0, np.cumsum(length)[:-1]]
v, w = command
horizon = monitor.command_bounds(v, w)['horizon_seconds']
# <= 2 cm nominal travel between samples, plus both endpoints. Body and
# support checks independently bound the continuous uncertain motion.
count = max(2, math.ceil(abs(v)*horizon/.02)+1)
times = np.linspace(0, horizon, count)
if abs(w) < 1e-9:
trace = np.c_[v*times, np.zeros(count)]
else:
trace = v/w*np.c_[np.sin(w*times), 1-np.cos(w*times)]
shift = trace[:, None, :] - a
fractions = np.clip(np.einsum('nsi,si->ns', shift, delta)/(length**2), 0, 1)
distance = np.linalg.norm(shift - fractions[:, :, None]*delta, axis=2)
closest = np.argmin(distance, axis=1)
progress = starts[closest] + fractions[np.arange(count), closest]*length[closest]
return bool(np.max(distance[np.arange(count), closest]) <= tolerance
and progress[-1] > progress[0] + .01
and np.min(np.diff(progress)) >= -.01)
def admit_forward_prefix(path, monitor, policy, terrain, pose, height, current_points,
*, lookahead_m, maximum_speed):
"""Prefer the chosen path curvature, then test gentler forward arcs.
This is a bounded fallback, not a reverse/turn recovery or obstacle waiver.
Its lateral tracking tolerance is half the narrower physical track width.
Every candidate must have completely observed stopping support. The live
controller repeats admission with the current pose and raw ranges.
"""
if monitor.contacts is None:
return None
centres = [(low[1]+high[1])/2 for low, high in monitor.contacts.bands]
base = forward_path_command(path, centres, lookahead_m=lookahead_m,
maximum_speed=min(maximum_speed, .3), maximum_yaw_rps=policy.partial_yaw_rps)
if base is None:
return None
tolerance = min(high[1]-low[1] for low, high in monitor.contacts.bands)/2
trials = []
# Two speed levels let a short prefix be followed without extending it.
for speed in dict.fromkeys((base[0], min(base[0], policy.partial_speed_mps))):
for factor in (1., .5, 0.):
yaw = speed * base[2]['curvature_per_m'] * factor
v, w, body_scale = monitor.regulate_command(speed, yaw, terrain, pose)
if body_scale == 0 or v <= 0:
continue
if not follows_prefix((v, w), path, monitor, tolerance):
continue
v, w, scale, ground = policy.regulate(v, w, terrain, pose, height,
current_points=current_points)
trials.append(dict(proposal=[speed, yaw], admitted=bool(scale > 0 and ground['admitted'])))
if scale == 0 or not ground['admitted']:
continue
if not follows_prefix((v, w), path, monitor, tolerance):
continue
return v, w, body_scale, scale, ground, dict(
phase='forward-path', method='velocity-sampling',
tracking_tolerance_m=tolerance, trials=trials,
authority='existing-prefix; full stopping support and live obstacle veto')
return None
@@ -0,0 +1,54 @@
// A smooth preference for space, independent of the hard swept-body veto.
// Known hazards only; missing ground never becomes a traversability grant.
#pragma once
#include <algorithm>
#include <cmath>
#include <utility>
#include <vector>
template <class TerrainCloud, class PathCloud>
double missioncoreClearancePreference(const TerrainCloud& terrain, const PathCloud& path,
double rotation, double scale, double range, double length, double width,
double threshold, double decayLength) {
if (!(decayLength > 0)) return 1.0;
const double halfLength = length / 2 - .05, halfWidth = width / 2 - .05;
const double cap = std::min(range, 1.2);
// At six decay lengths the remaining influence is below 0.25%.
const double influence = 6 * decayLength;
std::vector<std::pair<double,double>> hazards;
for (const auto& p : terrain.points)
if (p.intensity > threshold && std::hypot(p.x,p.y) <
cap + std::hypot(halfLength,halfWidth) + influence)
hazards.emplace_back(p.x,p.y);
if (hazards.empty()) return 1.0;
const double c = std::cos(rotation), s = std::sin(rotation);
double lastX = 0, lastY = 0, lastSample = -.1, penalty = 0;
int count = 0;
for (const auto& p : path.points) {
const double distance = std::hypot(p.x,p.y)*scale;
if (distance > cap) break;
const double x = scale*(c*p.x-s*p.y), y = scale*(s*p.x+c*p.y);
const double dx = x-lastX, dy = y-lastY;
if (std::hypot(dx,dy) < 1e-6) continue;
const double yaw = std::atan2(dy,dx);
lastX = x; lastY = y;
// Sample by distance, so dense path vertices don't bias the preference.
if (distance-lastSample < .1) continue;
lastSample = distance;
const double cy = std::cos(yaw), sy = std::sin(yaw);
double nearest = influence;
for (const auto& h : hazards) {
const double hx = h.first-x, hy = h.second-y;
const double along = std::max(0.0,std::abs(hx*cy+hy*sy)-halfLength);
const double across = std::max(0.0,std::abs(-hx*sy+hy*cy)-halfWidth);
nearest = std::min(nearest,std::hypot(along,across));
}
penalty += std::exp(-nearest/decayLength);
++count;
}
// Zero clearance must not retain a one-third score floor: that floor let
// goal direction dominate the clearance field beside a forbidden verge.
// Exponential free-space utility approaches zero continuously at contact.
// Positive narrow corridors remain candidates; the hard veto is separate.
return count ? std::max(1e-9, 1.0-penalty/count) : 1.0;
}
@@ -49,6 +49,10 @@ bool missioncoreFootprintClear(const TerrainCloud& terrain, const PathCloud& pat
lookYaw = rotation + std::atan2(p.y, p.x);
if (std::hypot(p.x, p.y) * scale >= std::min(0.7, cap)) break;
}
// A forward-only mission must not select a reversing primitive merely
// because its initial turn is collision-free. Reverse requires an explicit
// observed recovery grant, shared with pathFollower for this transaction.
if (!twoWayDrive && std::cos(lookYaw) < 0) return false;
// A reversing body follows the rear-facing primitive without first turning
// 180 degrees. Match pathFollower's twoWayDrive direction selection.
const bool reverse = twoWayDrive && std::cos(lookYaw) < 0;
@@ -0,0 +1,18 @@
#pragma once
#include <cmath>
// Score the endpoint bearing of the same prefix localPlanner publishes. The
// full lattice path's final heading is unrelated to a short, cropped target.
// Coordinates and limit are in the unscaled primitive frame. Rotation is
// applied by the existing selector, exactly as for the published trajectory.
template <class Cloud>
double missioncorePrefixDirection(const Cloud& path, double limit) {
double x = 0, y = 0;
for (const auto& point : path.points) {
const float distance = std::sqrt(point.x * point.x + point.y * point.y);
if (distance > limit) break;
x = point.x;
y = point.y;
}
return std::atan2(y, x) * 180.0 / std::acos(-1.0);
}
@@ -0,0 +1,14 @@
// Pure pursuit of the existing local path, in the current vehicle frame.
// Geometry determines curvature; changing speed must preserve the same arc.
// Rotation-in-place, acceleration, goal stop and safety gates remain owned by
// pathFollower and the independent live swept-body/support monitor.
#pragma once
#include <algorithm>
#include <cmath>
inline double missioncorePursuitYaw(double speed, double lateral,
double distance, double maxYaw) {
if (distance <= 1e-6) return 0.0;
const double yaw = speed * 2.0 * lateral / (distance * distance);
return std::max(-maxYaw, std::min(maxYaw, yaw));
}
@@ -0,0 +1,199 @@
"""Local intent from current range and causal multi-view surface observations.
Changing the camera sector must not move a still observed goal to that sector's
image centre. This selects measured points, never a route or permission to move;
the native planner still admits the complete commanded body sweep.
"""
import math
import numpy as np
from .semantic_surface import SemanticSurface
class ObservedGoals:
def __init__(self):
self.surface = SemanticSurface(retain_near=True)
self.evidence = None
def observe(self, samples, captured_at, pose):
self.surface.observe(samples, captured_at, pose)
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
"""Measured local destinations may temporarily move away from the task.
This removes the greedy progress constraint ONLY during a surveyed
recovery. It proposes a heading/destination, not a path or a clearance
receipt. The native planner and body/support guards remain mandatory.
"""
points = np.asarray(points, dtype=float).reshape(-1, 3)
if not len(points) or target is None:
return None
if prior is not None and prior.get("kind") == "orient":
# The viewing intent survives its source leaving the crop. Current
# range and full swept-body support still govern the actual pivot.
return prior
def inspect_heading():
# Nav-style Spin intent: inspect with front range sensors when the
# panoramic image has no usable metric correspondence (self occlusion
# included). These XY values encode a bearing, NEVER a drive goal.
x, y, z, w = pose[3:7]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
directions = [yaw+offset for offset in (math.pi/2, -math.pi/2, math.pi)]
views = [np.asarray(pose[:2])+2*geometry["length_m"]*np.array([math.cos(a),math.sin(a)])
for a in directions]
for xy in sorted(views, key=lambda p: math.dist(p, target)):
if all(math.dist(xy, p[:2]) > .6 for p in excluded):
return dict(goal=[*xy.tolist(), pose[2]-geometry["body_contact_height_m"]],
reverse=False, kind="orient")
return None
permitted = self.surface.permitted_terrain(points, now)
if not len(permitted):
return None if prior is not None else inspect_heading()
xy = np.asarray(pose[:2])
if prior is not None:
point = np.asarray(prior["goal"])
cell = tuple(self.surface.cell_keys(point[None])[0])
permission, stamp = self.surface.cells.get(cell, (0, -math.inf))
# The point may enter the near camera/range blind strip. Retain its
# causal intent only; current swept support still vetoes every tick.
if (permission != 1 or not self.surface.retained(cell, stamp, now)
or (candidate_mask is not None and not candidate_mask(point[None])[0])
or (math.dist(point[:2], xy) > .6
and not np.any(np.linalg.norm(permitted-point, axis=1) <= .2))):
return None
return prior
delta = permitted[:, :2] - xy
distance = np.linalg.norm(delta, axis=1)
good = (distance >= .6) & (distance <= 2 * geometry["length_m"])
good &= np.abs(permitted[:, 2] - (pose[2]-geometry["body_contact_height_m"])) <= (
geometry["max_step_m"] + distance*math.tan(math.radians(geometry["max_slope_degrees"])))
if candidate_mask is not None:
good &= candidate_mask(permitted)
for failed in excluded:
good &= np.linalg.norm(permitted[:, :2] - np.asarray(failed[:2]), axis=1) > .6
candidates = permitted[good]
if not len(candidates):
return inspect_heading()
x, y, z, w = pose[3:7]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
delta = candidates[:, :2] - xy
bearings = np.arctan2(delta[:, 1], delta[:, 0]) - yaw
errors = np.arctan2(np.sin(bearings), np.cos(bearings))
distance = np.linalg.norm(delta, axis=1)
# A short straight back-out is one option, alongside forward arcs and
# stopped pivots. It is never an obligatory first recovery action.
reverse = (np.abs(errors) > math.pi-.12) & (distance <= .8)
turning = np.where(reverse, math.pi-np.abs(errors), np.abs(errors))
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
offsets = np.linspace(-geometry["width_m"]/2, geometry["width_m"]/2,
math.ceil(geometry["width_m"]/.1)+1)
# Search once per 20 cm observed cell, not every duplicate ray return.
tried = set()
for i in np.argsort(score, kind="stable"):
point = candidates[i]
key = tuple(self.surface.cell_keys(point[None])[0])
if key in tried:
continue
tried.add(key)
forward = delta[i]/distance[i]
lateral = np.array([-forward[1], forward[0]])
across = point[:2]+offsets[:, None]*lateral
distances = np.linalg.norm(across[:, None, :]-permitted[None, :, :2], axis=2)
nearest = np.argmin(distances, axis=1)
if np.any(distances[np.arange(len(across)), nearest] > .15):
continue
heights = permitted[nearest, 2]
fit = np.polyfit(offsets, heights, 1)
if (abs(fit[0]) > math.tan(math.radians(geometry["max_slope_degrees"]))
or np.max(np.abs(heights-np.polyval(fit, offsets))) > .05):
continue
self.evidence = dict(source="surveyed-local-maneuver", goal=point.tolist(),
reverse=bool(reverse[i]), authority="intent-only; live native admission required")
return dict(goal=point.tolist(), reverse=bool(reverse[i]))
# A visible permitted sector can be too narrow/sparse to establish a
# translation destination while still being worth inspecting with the
# front depth sensors. This grants ONLY an orientation intent. Neither
# the point nor the camera survey certifies the ground under a pivot.
for i in np.argsort(score, kind="stable"):
if abs(errors[i]) >= math.radians(30):
return dict(goal=candidates[i].tolist(), reverse=False, kind="orient")
return inspect_heading()
def choose(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
self.evidence = None
if target is None:
return None
points, pose, target = map(lambda x: np.asarray(x, dtype=float), (points, pose, target))
if points.ndim != 2 or points.shape[1] != 3 or not np.isfinite(points).all():
raise ValueError("Invalid observed goal range")
if not len(points):
return None
direction = target - pose[:2]
remaining = float(np.linalg.norm(direction))
if remaining <= 0.4:
return None # Exact arrival remains the native whole-body receipt.
forward = direction / remaining
lateral = np.array([-forward[1], forward[0]])
delta = points[:, :2] - pose[:2]
distance = np.linalg.norm(delta, axis=1)
progress = np.linalg.norm(points[:, :2] - target, axis=1)
good = (
(distance >= 0.4) & (distance <= 3.5) & (progress < remaining - 0.1)
& (np.abs(points[:, 2] - (pose[2] - geometry["body_contact_height_m"]))
<= distance * math.tan(math.radians(geometry["max_slope_degrees"])))
)
if candidate_mask is not None:
good &= candidate_mask(points)
for failed in excluded:
good &= np.linalg.norm(points[:, :2] - np.asarray(failed[:2]), axis=1) > 0.6
candidates = points[good]
if len(candidates) < 8:
return None
allowed = {
key: stamp for key, (permission, stamp) in self.surface.cells.items()
if permission == 1 and self.surface.retained(key, stamp, now)
}
candidates = candidates[[tuple(key) in allowed
for key in self.surface.cell_keys(candidates)]]
if not len(candidates):
return None
offsets = np.linspace(-geometry["width_m"] / 2, geometry["width_m"] / 2,
math.ceil(geometry["width_m"] / 0.1) + 1)
def supported(point):
across = point[:2] + offsets[:, None] * lateral
# Bind each lateral query to measured, permitted ground at its own
# height. Do not copy the centre elevation across a cross-slope or
# project a sidewalk label through an overhang onto another floor.
distances = np.linalg.norm(across[:,None,:]-candidates[None,:,:2],axis=2)
nearest = np.argmin(distances,axis=1)
if np.any(distances[np.arange(len(across)),nearest] > .15):
return False
keys = [tuple(cell) for cell in self.surface.cell_keys(candidates[nearest])]
self.evidence = {
"source": "current-range-and-observed-semantic-memory",
"goal": point.tolist(),
"oldest_surface_age_seconds": max(now - allowed[key] for key in keys),
"authority": "intent-only; native swept-obstacle-and-support-admission-required",
}
return True
# A lens switch cannot replace a currently measured, permitted goal.
# A new prohibition, missing current range or changed corridor can.
if prior is not None:
before = np.asarray(prior, dtype=float)
matched = np.linalg.norm(candidates - before, axis=1) <= 0.15
if (math.dist(before[:2], pose[:2]) > 0.8 and matched.any()
and all(math.dist(before[:2], failed[:2]) > 0.6 for failed in excluded)
and (candidate_mask is None or candidate_mask(before[None])[0])
and supported(before)):
return before.tolist()
distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1)
# The declared task, not the selected lens, owns the preferred direction.
score = distance_to_target + 2 * np.abs((candidates[:, :2] - pose[:2]) @ lateral)
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
return candidates[index].tolist()
return None
@@ -0,0 +1,46 @@
"""Reconcile coarse elevation costs using measured local ground patches.
CMU's low-quantile reference spans a wider neighborhood than a contact patch.
A nearby depression can give a level sidewalk a high cost. Only low returns
near the measured body contact plane are candidates; their complete measured
neighborhood must independently pass the existing support estimator. This runs
before semantic/object overlays and never fills an unobserved ground region.
"""
import math
import numpy as np
if __package__:
from .support_surface import SupportSurface
else:
from support_surface import SupportSurface
def observed_ground_costs(terrain, pose, contact_height_m, *, monitor):
terrain = np.asarray(terrain)
pose = np.asarray(pose, dtype=float)
if (terrain.ndim != 2 or terrain.shape[1] != 4 or pose.shape != (7,)
or not np.isfinite(terrain).all() or not np.isfinite(pose).all()):
raise ValueError("Invalid observed ground cost input")
x, y, z, w = pose[3:]
up = np.array([2*(x*z+w*y), 2*(y*z-w*x), 1-2*(x*x+y*y)])
height = (terrain[:, :3]-pose[:3]) @ up + contact_height_m
band = min(.08, .8*monitor.max_step)
candidates = (terrain[:, 3] > monitor.max_step+1e-4) & (np.abs(height) <= band)
if not candidates.any() or up[2] < 1/math.sqrt(1+monitor.max_slope**2):
return terrain, 0
# Separate raised objects from the ground fit, as the live range guard
# does. Otherwise a wall/bench column tilts the fit of the pavement beside
# it, and that pavement becomes a phantom solid obstacle in path search.
# Raised returns retain their ORIGINAL costs; negative returns remain in
# the fit, so this cannot erase a drop or manufacture its floor.
ground_cost = np.where(height > monitor.max_step+1e-4, monitor.max_step+1, 0)
surface = SupportSurface(np.column_stack((terrain[:, :3], ground_cost)),
pose, contact_height_m, monitor.max_step, monitor.max_slope,
anchor_radius_m=math.hypot(monitor.half_length, monitor.half_width))
indices = np.flatnonzero(candidates)
states, _ = surface.classify(terrain[indices, :2]-pose[:2])
accepted = indices[states == "observed-supported"]
result = terrain.copy()
result[accepted, 3] = np.abs(height[accepted])
return result, len(accepted)
@@ -0,0 +1,175 @@
"""Causal range memory: clear only measured free space, retain occluded near field.
Organized sensors clear whole 6 cm voxels through calibrated range images;
legacy packets use traversed ray voxels. A missing observation grants no
clearing. Endpoints are inserted afterwards, so current occupied evidence wins.
Scene identities, hidden geometry and qualification fixtures never enter here.
"""
import math
import numpy as np
if __package__:
from .range_image import RangeImages, VIEW_FIELDS
else:
from range_image import RangeImages, VIEW_FIELDS
class ObservedSpace:
voxel_m = 0.06
endpoint_margin_m = 0.12
near_memory_m = 4.0
far_decay_seconds = 2.0
maximum_observation_points = 30000
# A persistent 360-degree map is not one sensor packet. Bound its storage
# separately (128K occupied voxels), retaining the existing spatial/age
# window and fail-closed overflow. Never evict a near hazard to fit a frame.
maximum_cells = 131072
def __init__(self):
self.cells = {}
self.last_time = None
self.metrics = {}
def keys(self, points):
grid = np.floor(np.asarray(points, dtype=float) / self.voxel_m)
if not np.isfinite(grid).all() or np.any(np.abs(grid) >= 2**20):
raise ValueError("Range memory coordinate envelope exceeded")
cells = grid.astype(np.int64)
cells += 2**20
return (cells[..., 0] << 42) | (cells[..., 1] << 21) | cells[..., 2]
def free_keys(self, origins, ends, origin_indices=None):
if origins is None and ends is None:
return np.empty(0, dtype=np.int64)
origins, ends = np.asarray(origins, dtype=float), np.asarray(ends, dtype=float)
if origin_indices is not None:
indices = np.asarray(origin_indices)
if (
origins.ndim != 2
or origins.shape[1] != 3
or indices.ndim != 1
or len(indices) > 8000
or (len(indices) and not np.issubdtype(indices.dtype, np.integer))
or np.any(indices < 0)
or np.any(indices >= len(origins))
):
raise ValueError("Invalid range-ray mount indices")
origins = origins[indices.astype(np.int64)]
if origins.size == ends.size == 0:
return np.empty(0, dtype=np.int64)
if (
origins.ndim != 2
or origins.shape[1] != 3
or ends.shape != origins.shape
or len(origins) > 8000
or not np.isfinite(origins).all()
or not np.isfinite(ends).all()
):
raise ValueError("Invalid observed range-ray packet")
delta = ends - origins
ranges = np.linalg.norm(delta, axis=1)
if np.any(ranges > 8.01):
raise ValueError("Range ray exceeds the declared sensor envelope")
# Amanatides-Woo traversal: fixed-distance sampling misses arbitrarily
# short crossings near voxel edges and leaves permanent ghost walls.
# Traverse the measured open segment only; never dilate its free space.
valid = ranges > 2*self.endpoint_margin_m
directions = delta[valid] / ranges[valid, None]
starts = origins[valid] + self.endpoint_margin_m*directions
lengths = ranges[valid] - 2*self.endpoint_margin_m
if not len(lengths):
return np.empty(0, dtype=np.int64)
self.keys(starts) # Validate the same coordinate envelope before packing.
self.keys(starts + lengths[:,None]*directions)
cells = np.floor(starts / self.voxel_m).astype(np.int64)
signs = np.sign(directions).astype(np.int64)
increments = np.divide(self.voxel_m, np.abs(directions),
out=np.full_like(directions, np.inf), where=directions != 0)
boundary = (cells + (signs > 0))*self.voxel_m
crossings = np.divide(boundary-starts, directions,
out=np.full_like(directions, np.inf), where=directions != 0)
entered = np.zeros(len(cells))
active = np.ones(len(cells), dtype=bool)
keys = []
bound = math.ceil(float(lengths.max())*math.sqrt(3)/self.voxel_m)+4
for _ in range(bound):
leaving = crossings.min(axis=1)
occupied_segment = active & (np.minimum(leaving,lengths) > entered + 1e-12)
grid = cells[occupied_segment] + 2**20
keys.append((grid[:,0] << 42) | (grid[:,1] << 21) | grid[:,2])
active &= leaving < lengths - 1e-12
if not active.any():
break
crossed = (crossings <= leaving[:,None] + 1e-12) & active[:,None]
cells += signs*crossed
crossings += np.where(crossed, increments, 0)
entered = leaving
else:
raise RuntimeError("Range traversal exceeded its geometric bound")
return np.unique(np.concatenate(keys)) if keys else np.empty(0, dtype=np.int64)
def observe(self, points, pose, now, origins=None, ends=None, origin_indices=None,
*, range_views=None):
points, pose = np.asarray(points, dtype=float), np.asarray(pose, dtype=float)
if (
points.ndim != 2
or points.shape[1] != 3
or len(points) > self.maximum_observation_points
or not np.isfinite(points).all()
or pose.shape != (7,)
or not np.isfinite(pose).all()
or not math.isfinite(now)
or (self.last_time is not None and now < self.last_time)
):
raise ValueError("Invalid causal range-memory observation")
occupied = self.keys(points)
images = None
if range_views is not None and any(key in range_views for key in VIEW_FIELDS):
if not all(key in range_views for key in VIEW_FIELDS):
raise ValueError("Incomplete organized range packet")
images = RangeImages(origins, range_views)
free = (np.empty(0, dtype=np.int64) if images is not None else
self.free_keys(origins, ends, origin_indices))
before, removed = len(self.cells), 0
if self.cells:
keys = np.fromiter(self.cells, dtype=np.int64)
cleared = (images.cleared([point for point, _ in self.cells.values()],
self.voxel_m, self.endpoint_margin_m)
if images is not None else np.isin(keys, free))
for key in keys[cleared]:
del self.cells[int(key)]
removed += 1
for key, point in zip(occupied, points, strict=True):
# A row view would keep its entire source frame alive as long as
# any one voxel survived, and permit later input mutation to alter
# history. Each voxel owns only its three measured coordinates.
self.cells[int(key)] = (point.copy(), now)
# Do not allocate a NumPy vector in a Python loop for every retained
# return on every frame. The same age/distance rule is vectorized.
cell_keys = np.fromiter(self.cells, dtype=np.int64)
observations = list(self.cells.values())
retained_points = np.asarray([item[0] for item in observations], dtype=np.float64).reshape(-1, 3)
seen = np.fromiter((item[1] for item in observations), dtype=float)
expired = cell_keys[
(now - seen > self.far_decay_seconds)
& (np.hypot(retained_points[:, 0] - pose[0], retained_points[:, 1] - pose[1])
>= self.near_memory_m)
]
for key in expired:
del self.cells[int(key)]
if len(self.cells) > self.maximum_cells:
raise RuntimeError("Range memory capacity exceeded; refusing blind eviction")
self.last_time = now
self.metrics = {
"cells_before": before,
"cleared_by_rays": removed,
"clearing_model": "projective-full-voxel/v1" if images is not None else "ray-voxel/v1",
"expired_far_cells": len(expired),
"retained_cells": len(self.cells),
"observed_rays": 0 if ends is None else len(ends),
}
return np.asarray([point for point, _ in self.cells.values()], dtype=np.float32).reshape(
-1, 3
)
@@ -0,0 +1,35 @@
"""Add cost-aware free-space preference to the pinned CMU primitive selector."""
from pathlib import Path
def patch(source):
if "missioncoreClearancePreference" in source:
raise ValueError("Clearance preference already present")
include = '#include "missioncore_footprint.hpp"'
declaration = ' nh->declare_parameter<double>("vehicleWidth", vehicleWidth);'
getter = ' nh->get_parameter("vehicleWidth", vehicleWidth);'
edits = {
include: '#include "missioncore_clearance.hpp"\ndouble footprintClearanceScale = 0;\n' + include,
declaration: ' nh->declare_parameter<double>("footprintClearanceScale", footprintClearanceScale);\n' + declaration,
getter: ' nh->get_parameter("footprintClearanceScale", footprintClearanceScale);\n' + getter,
" maxScore = clearPathPerGroupScore[i];": ''' // Rank only candidates that passed the hard body veto above.
// In blocked space evaluating the soft field for every rejected
// primitive at every reduced range can starve the sensor lease.
const double candidateScore = clearPathPerGroupScore[i] *
missioncoreClearancePreference(*plannerFootprintCloud,
*startPaths[i % groupNum], rotAng, pathScale,
std::min(pathRange, relativeGoalDis), vehicleLength, vehicleWidth,
obstacleHeightThre, footprintClearanceScale);
if (candidateScore <= maxScore) continue;
maxScore = candidateScore;''',
}
for anchor, replacement in edits.items():
if source.count(anchor) != 1:
raise ValueError("Unexpected pinned CMU clearance anchor: " + anchor)
source = source.replace(anchor, replacement)
return source
if __name__ == "__main__":
path = Path("/opt/cmu/src/local_planner/src/localPlanner.cpp")
path.write_text(patch(path.read_text()))
@@ -0,0 +1,38 @@
"""Opt-in world-frame paths for CMU's existing live-odometry path follower."""
from pathlib import Path
def patch(source):
edits = {
"bool pathInit = false;": "bool pathInit = false;\nbool pathInMapFrame = false;",
' nh->declare_parameter<double>("lookAheadDis", lookAheadDis);':
' nh->declare_parameter<bool>("pathInMapFrame", pathInMapFrame);\n'
' nh->declare_parameter<double>("lookAheadDis", lookAheadDis);',
' nh->get_parameter("lookAheadDis", lookAheadDis);':
' nh->get_parameter("pathInMapFrame", pathInMapFrame);\n'
' nh->get_parameter("lookAheadDis", lookAheadDis);',
" vehicleXRec = vehicleX;": """ if (pathInMapFrame) {
if (pathIn->header.frame_id != "map") { pathInit = false; return; }
const double c = cos(vehicleYaw), s = sin(vehicleYaw);
for (int i = 0; i < pathSize; i++) {
const double x = path.poses[i].pose.position.x - vehicleX;
const double y = path.poses[i].pose.position.y - vehicleY;
path.poses[i].pose.position.x = c * x + s * y;
path.poses[i].pose.position.y = -s * x + c * y;
path.poses[i].pose.position.z -= vehicleZ;
}
}
vehicleXRec = vehicleX;""",
}
for anchor, replacement in edits.items():
if source.count(anchor) != 1:
raise ValueError("Unexpected pinned CMU continuous anchor: " + anchor)
source = source.replace(anchor, replacement)
return source
if __name__ == "__main__":
path = Path("/opt/cmu/src/local_planner/src/pathFollower.cpp")
path.write_text(patch(path.read_text()))
@@ -0,0 +1,51 @@
"""Preserve measured hazard positions for CMU's final primitive veto.
Voxel centroids remain useful for ranking primitives, but can move an obstacle
away from a chassis corner. The selector and downstream guard must see the
same unaveraged terrain snapshot. Laser-only mode and explicit boundaries keep
their existing semantics.
"""
from pathlib import Path
def patch(source):
if "plannerFootprintCloud" in source:
raise ValueError("Dense footprint patch already present")
declaration = "pcl::VoxelGrid<pcl::PointXYZI> laserDwzFilter, terrainDwzFilter;"
boundary = " int boundaryCloudSize = boundaryCloud->points.size();"
selector = "missioncoreFootprintClear(*plannerCloudCrop, *startPaths[i % groupNum],"
additions = """ if (dis < adjacentRange) {
plannerCloudCrop->push_back(point);
}"""
for anchor, count in ((declaration, 1), (boundary, 1), (selector, 1), (additions, 2)):
if source.count(anchor) != count:
raise ValueError("Unexpected pinned CMU dense footprint anchor")
source = source.replace(declaration, declaration + "\n"
"pcl::PointCloud<pcl::PointXYZI>::Ptr plannerFootprintCloud(new pcl::PointCloud<pcl::PointXYZI>());")
source = source.replace(boundary, """ // Use the same pose and raw terrain snapshot as the command guard.
// Never average hazard positions or intensities for the body veto.
plannerFootprintCloud->clear();
if (useTerrainAnalysis) {
for (const auto& raw : terrainCloudCrop->points) {
const float dx = raw.x - vehicleX, dy = raw.y - vehicleY;
point.x = dx * cosVehicleYaw + dy * sinVehicleYaw;
point.y = -dx * sinVehicleYaw + dy * cosVehicleYaw;
point.z = raw.z - vehicleZ;
point.intensity = raw.intensity;
if (std::hypot(point.x, point.y) < adjacentRange)
plannerFootprintCloud->push_back(point);
}
} else {
*plannerFootprintCloud = *plannerCloudCrop;
}
""" + boundary)
source = source.replace(additions, additions.replace(
"plannerCloudCrop->push_back(point);", "plannerCloudCrop->push_back(point);\n"
" plannerFootprintCloud->push_back(point);"))
return source.replace(selector, selector.replace("*plannerCloudCrop", "*plannerFootprintCloud"))
if __name__ == "__main__":
path = Path("/opt/cmu/src/local_planner/src/localPlanner.cpp")
path.write_text(patch(path.read_text()))
@@ -0,0 +1,39 @@
"""Add acknowledged direction admission to the pinned CMU ROS nodes."""
from pathlib import Path
def patch(source, follower=False):
anchor = ' nh->get_parameter("twoWayDrive", twoWayDrive);'
if source.count(anchor) != 1:
raise ValueError("Unexpected pinned CMU direction parameter")
reset = (
"navFwd = true; vehicleSpeed = 0; vehicleYawRate = 0; pathInit = false;" if follower else ""
)
callback = """
auto directionPolicy = nh->add_on_set_parameters_callback(
[](const std::vector<rclcpp::Parameter>& parameters) {
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
for (const auto& parameter : parameters) {
if (parameter.get_name() == "twoWayDrive") {
if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_BOOL) {
result.successful = false;
result.reason = "Direction permission must be boolean";
return result;
}
twoWayDrive = parameter.as_bool();
RESET
}
}
return result;
});
""".replace("RESET", reset)
return source.replace(anchor, anchor + callback)
if __name__ == "__main__":
root = Path("/opt/cmu/src/local_planner/src")
for name in ("localPlanner", "pathFollower"):
path = root / f"{name}.cpp"
path.write_text(patch(path.read_text(), name == "pathFollower"))
@@ -0,0 +1,38 @@
"""Make CMU goal ranking agree with its published cropped primitive."""
from pathlib import Path
def patch(source):
if "missioncorePrefixDirection" in source:
raise ValueError("Prefix goal direction already present")
include = '#include "missioncore_footprint.hpp"'
declaration = ' nh->declare_parameter<double>("vehicleWidth", vehicleWidth);'
getter = ' nh->get_parameter("vehicleWidth", vehicleWidth);'
direction = ' float dirDiff = fabs(joyDir - endDirPathList[i % pathNum] - (10.0 * rotDir - 180.0));'
edits = {
include: '#include "missioncore_prefix.hpp"\nbool usePrefixGoalDirection = false;\n' + include,
declaration: ' nh->declare_parameter<bool>("usePrefixGoalDirection", usePrefixGoalDirection);\n' + declaration,
getter: ' nh->get_parameter("usePrefixGoalDirection", usePrefixGoalDirection);\n' + getter,
' if (minObsAngCW > 0) minObsAngCW = 0;': ''' double prefixDirection[groupNum] = {0};
if (usePrefixGoalDirection) {
for (int group = 0; group < groupNum; ++group) {
prefixDirection[group] = missioncorePrefixDirection(*startPaths[group],
std::min(pathRange, relativeGoalDis) / pathScale);
}
}
if (minObsAngCW > 0) minObsAngCW = 0;''',
direction: ''' const double goalDirection = usePrefixGoalDirection
? prefixDirection[pathList[i % pathNum]] : endDirPathList[i % pathNum];
float dirDiff = fabs(joyDir - goalDirection - (10.0 * rotDir - 180.0));''',
}
for anchor, replacement in edits.items():
if source.count(anchor) != 1:
raise ValueError("Unexpected pinned CMU prefix anchor: " + anchor)
source = source.replace(anchor, replacement)
return source
if __name__ == "__main__":
path = Path("/opt/cmu/src/local_planner/src/localPlanner.cpp")
path.write_text(patch(path.read_text()))
@@ -0,0 +1,46 @@
"""Opt-in curvature tracking in the pinned CMU follower, for both control loops.
CMU's heading-proportional angular command is independent of speed. On a slow
tracked robot it asks for a much tighter arc than the selected primitive and
can be vetoed forever beside a safe corridor. Use the pure-pursuit curvature
of its existing look-ahead point during translation. Keep the original separate
large-heading rotation, direction grant, speed ramp and all subsequent stops.
"""
from pathlib import Path
def patch(source):
if "usePurePursuit" in source or "missioncorePursuitYaw" in source:
raise ValueError("Pursuit adapter already present")
edits = {
"bool pathInit = false;":
'#include "missioncore_pursuit.hpp"\n'
'bool usePurePursuit = false;\nbool pathInit = false;',
' nh->declare_parameter<double>("lookAheadDis", lookAheadDis);':
' nh->declare_parameter<bool>("usePurePursuit", usePurePursuit);\n'
' nh->declare_parameter<double>("lookAheadDis", lookAheadDis);',
' nh->get_parameter("lookAheadDis", lookAheadDis);':
' nh->get_parameter<bool>("usePurePursuit", usePurePursuit);\n'
' nh->get_parameter("lookAheadDis", lookAheadDis);',
' if (odomTime < stopInitTime + stopTime && stopInitTime > 0) {':
''' if (usePurePursuit && autonomyMode && pathSize > 1 &&
fabs(dirDiff) < dirDiffThre && dis > stopDisThre) {
const double heading = vehicleYaw - vehicleYawRec;
const double lateral = -sin(heading) * disX + cos(heading) * disY;
vehicleYawRate = missioncorePursuitYaw(vehicleSpeed, lateral, dis,
maxYawRate * PI / 180.0);
}
if (odomTime < stopInitTime + stopTime && stopInitTime > 0) {''',
}
for anchor, replacement in edits.items():
if source.count(anchor) != 1:
raise ValueError("Unexpected pinned CMU pursuit anchor: " + anchor)
source = source.replace(anchor, replacement)
return source
if __name__ == "__main__":
path = Path("/opt/cmu/src/local_planner/src/pathFollower.cpp")
path.write_text(patch(path.read_text()))
@@ -0,0 +1,43 @@
"""Explicit full-map input mode for the pinned upstream terrain analysis."""
from pathlib import Path
def patch(source):
declaration = ' nh->declare_parameter<double>("scanVoxelSize", scanVoxelSize);'
getter = ' nh->get_parameter("scanVoxelSize", scanVoxelSize);'
stack = " // stack registered laser scans"
edits = {
"bool clearingCloud = false;": (
"bool clearingCloud = false;\nbool inputIsMapSnapshot = false;"
),
declaration: (
' nh->declare_parameter<bool>("inputIsMapSnapshot", inputIsMapSnapshot);\n'
+ declaration
),
getter: (' nh->get_parameter("inputIsMapSnapshot", inputIsMapSnapshot);\n' + getter),
stack: """ // ObservedSpace owns memory and ray clearing.
// A complete
// snapshot replaces our staging clouds, never averages timestamps with
// older copies or resurrects endpoints removed by the upstream memory.
if (inputIsMapSnapshot) {
for (int ind = 0; ind < terrainVoxelNum; ind++) {
terrainVoxelCloud[ind]->clear();
terrainVoxelUpdateNum[ind] = 0;
}
}
// stack registered laser scans""",
}
if "inputIsMapSnapshot" in source:
raise ValueError("CMU snapshot patch already present")
for anchor, replacement in edits.items():
if source.count(anchor) != 1:
raise ValueError("Unexpected pinned CMU snapshot anchor")
source = source.replace(anchor, replacement)
return source
if __name__ == "__main__":
path = Path("/opt/cmu/src/terrain_analysis/src/terrainAnalysis.cpp")
path.write_text(patch(path.read_text()))
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 3.16)
project(ndc_pcl_ground LANGUAGES C CXX)
find_package(PCL 1.12 REQUIRED COMPONENTS segmentation)
add_library(pcl_ground SHARED pcl_ground.cpp)
target_compile_features(pcl_ground PRIVATE cxx_std_17)
target_include_directories(pcl_ground SYSTEM PRIVATE ${PCL_INCLUDE_DIRS})
target_link_libraries(pcl_ground PRIVATE ${PCL_LIBRARIES})
target_compile_options(pcl_ground PRIVATE ${PCL_DEFINITIONS})
set_target_properties(pcl_ground PROPERTIES LIBRARY_OUTPUT_DIRECTORY /opt/missioncore)
file(WRITE /opt/missioncore/pcl-version.txt "${PCL_VERSION}\n")
@@ -0,0 +1,36 @@
// PCL segmentation only: source indices and plane, with no motion authority.
#include <pcl/point_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <cmath>
extern "C" int pcl_ground_indices(const float *xyz, int count, float angle,
float distance, int *output,
float *coefficients) noexcept {
try {
if (count < 3 || count > 30000 || !std::isfinite(angle) || angle <= 0 ||
!std::isfinite(distance) || distance <= 0) return -1;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
cloud->reserve(count);
for (int i = 0; i < count; ++i) {
const float *p = xyz + 3*i;
if (!std::isfinite(p[0]) || !std::isfinite(p[1]) || !std::isfinite(p[2])) return -1;
cloud->push_back(pcl::PointXYZ(p[0], p[1], p[2]));
}
pcl::SACSegmentation<pcl::PointXYZ> filter;
filter.setInputCloud(cloud);
filter.setModelType(pcl::SACMODEL_PERPENDICULAR_PLANE);
filter.setMethodType(pcl::SAC_RANSAC);
filter.setAxis(Eigen::Vector3f::UnitZ());
filter.setEpsAngle(angle);
filter.setDistanceThreshold(distance);
filter.setOptimizeCoefficients(true);
filter.setMaxIterations(100);
pcl::PointIndices indices;
pcl::ModelCoefficients model;
filter.segment(indices, model);
if (model.values.size() != 4) return 0;
for (int i = 0; i < 4; ++i) coefficients[i] = model.values[i];
for (size_t i = 0; i < indices.indices.size(); ++i) output[i] = indices.indices[i];
return static_cast<int>(indices.indices.size());
} catch (...) { return -1; }
}
@@ -0,0 +1,48 @@
"""PCL plane inliers for ROI refinement; raw geometry remains unchanged."""
import ctypes
import math
import numpy as np
class PclGround:
height_m = .05
def __init__(self, geometry):
self.library = ctypes.CDLL('/opt/missioncore/libpcl_ground.so')
self.extract = self.library.pcl_ground_indices
self.extract.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int,
ctypes.c_float, ctypes.c_float, ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_float)]
self.extract.restype = ctypes.c_int
self.angle = math.radians(geometry['max_slope_degrees'])
def mask(self, points, *, ground_anchor=None):
points = np.ascontiguousarray(points, dtype=np.float32)
if (points.ndim != 2 or points.shape[1] != 3 or len(points) > 30000
or not np.isfinite(points).all()):
raise ValueError('Invalid PCL ground input')
result = np.zeros(len(points), dtype=bool)
if len(points) < 3:
return result
indices = np.empty(len(points), np.int32)
model = np.zeros(4, np.float32)
count = self.extract(points.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
len(points), self.angle, self.height_m,
indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int)),
model.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))
if not 0 <= count <= len(points):
raise RuntimeError('PCL ground segmentation failed')
selected = indices[:count]
if np.any(selected < 0) or np.any(selected >= len(points)):
raise RuntimeError('PCL returned an invalid source index')
# A horizontal tabletop / another floor is not the rover's ground.
# Without a matching measured contact reference no association clears.
if ground_anchor is not None:
anchor = np.asarray(ground_anchor, dtype=float)
if anchor.shape != (3,) or not np.isfinite(anchor).all():
raise ValueError('Invalid ground reference')
if abs(anchor @ model[:3] + model[3]) > self.height_m:
return result
result[selected] = True
return result
@@ -2,6 +2,7 @@
import argparse
import json
import time
from pathlib import Path
import numpy as np
@@ -9,6 +10,7 @@ import terrain_costs as costs
parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--terrain", type=Path)
args = parser.parse_args()
assert costs._NATIVE is not None, "Compiled implementation must be installed"
engine = costs._NATIVE
@@ -27,5 +29,52 @@ for points in cases:
expected = costs.connected_grade(points)
costs._NATIVE = engine
assert costs.connected_grade(points) == expected
args.output.write_text(json.dumps({"passed": True, "cases": len(cases)}))
print(json.dumps({"passed": True, "cases": len(cases)}))
neighborhood_cases = 0
for dtype in (np.float32, np.float64):
for offset in (0, -240, 1000):
points = rng.uniform(-2, 2, (600, 4)).astype(dtype)
points[:, :2] += offset
# Include exact radius/cell boundaries, negative cells and duplicates.
points[:7, :3] = (
np.array(
[
[0, 0, 0],
[0.4, 0, 0],
[-0.4, 0, 0],
[0.399999, 0, 0],
[0.400001, 0, 0],
[0, 0.4, 0],
[0, 0, 0],
],
dtype=dtype,
)
+ offset
)
reference = costs._reference_neighborhoods(points)
native = costs._NativeNeighborhoods(points)
for index in range(len(points)):
assert np.array_equal(native(index), reference(index)), (dtype, offset, index)
neighborhood_cases += 1
costs._NATIVE = None
expected, count = costs.supported_slope_costs(points)
costs._NATIVE = engine
actual, native_count = costs.supported_slope_costs(points)
assert native_count == count and np.array_equal(actual, expected)
timings = {}
if args.terrain:
terrain = np.load(args.terrain)
for name, implementation in (("reference", None), ("native", engine)):
costs._NATIVE = implementation
normalize = costs.TerrainCostNormalizer()
timings[name] = []
for _ in range(5):
started = time.monotonic()
result, corrected = normalize(terrain)
timings[name].append((time.monotonic() - started) * 1000)
if name == "reference":
expected, count = result, corrected
else:
assert np.array_equal(result, expected) and count == corrected
report = dict(passed=True, cases=len(cases), neighborhoods=neighborhood_cases, timings_ms=timings)
args.output.write_text(json.dumps(report))
print(json.dumps(report))
@@ -0,0 +1,121 @@
"""Worker-only check of forward/recovery permission transitions in real ROS nodes."""
import argparse
import datetime as dt
import http.client
import json
import subprocess
import time
from pathlib import Path
from uuid import uuid4
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--adapter", type=Path, required=True)
parser.add_argument("--image", required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
container = "ndc-mission-core-direction-check-" + uuid4().hex[:8]
report = dict(
utc=dt.datetime.now(dt.timezone.utc).isoformat(), # noqa: UP017
monotonic=time.monotonic(),
image=args.image,
cases=[],
)
connection = http.client.HTTPConnection("127.0.0.1", 18193, timeout=3)
def request(path, body=None):
connection.request(
"GET" if body is None else "POST", path, body=None if body is None else json.dumps(body)
)
response = connection.getresponse()
value = json.loads(response.read())
if response.status != 200:
raise RuntimeError(str(value))
return value
try:
subprocess.run(
[
"docker",
"run",
"-d",
"--name",
container,
"--cpus",
"3",
"--memory",
"2g",
"--label",
"com.nodedc.product=mission-core",
"--label",
"com.nodedc.stack=ai-polygon-qualification",
"--label",
"com.nodedc.role=qualification",
"--label",
"com.nodedc.managed-by=ai-polygon-qualification",
"-p",
"127.0.0.1:18193:8010",
"--mount",
f"type=bind,source={args.adapter},target=/adapter,readonly",
args.image,
],
check=True,
capture_output=True,
)
deadline = time.monotonic() + 20
while True:
try:
request("/ready")
break
except (OSError, RuntimeError, http.client.HTTPException):
if time.monotonic() > deadline:
raise
time.sleep(0.2)
floor = [[x / 10, y / 10, 0] for x in range(-25, 41) for y in range(-25, 26)]
# Do not reset between directions: revoking recovery must also clear
# the follower's latched navFwd state and require a fresh path.
for name, reverse, goal in (
("forward", False, [3, 0, 0]),
("recovery", True, [-0.65, 0, 0]),
("forward-near-left", False, [0.15, 0.55, 0]),
("recovery-again", True, [-0.65, 0, 0]),
("forward-restored", False, [3, 0, 0]),
):
samples = []
for _ in range(16):
samples.append(
request(
"/plan",
dict(
points=floor,
pose=[0, 0, 0.37, 0, 0, 0, 1],
goal=goal,
allow_reverse=reverse,
max_speed_mps=0.15,
),
)
)
time.sleep(0.1)
tail = samples[-5:]
if reverse:
passed = all(s["speed_mps"] < -0.05 for s in tail)
elif name == "forward-near-left":
passed = all(s["yaw_rate_rps"] > 0.1 and s["speed_mps"] >= 0 for s in tail)
else:
passed = all(s["speed_mps"] > 0.05 for s in tail)
report["cases"].append(dict(name=name, passed=passed, samples=samples))
report["passed"] = all(c["passed"] for c in report["cases"])
finally:
connection.close()
# The local case name must never replace the owned container name.
subprocess.run(["docker", "rm", "-f", container], capture_output=True)
args.output.write_text(json.dumps(report, indent=2))
print(json.dumps({"passed": report["passed"], "cases": len(report["cases"])}))
if not report["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,98 @@
"""Bounded CPU replay of archived range for geometry-processing diagnostics.
Run in an isolated navigation container, with no vehicle or GPU authority.
This measures the terrain adapter, not route or semantic acceptance.
"""
import argparse
import cProfile
import datetime as dt
import hashlib
import http.client
import json
import pstats
import time
from pathlib import Path
import numpy as np
from terrain_costs import TerrainCostNormalizer
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--run", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--first-frame", type=int, required=True)
parser.add_argument("--limit", type=int, default=80)
args = parser.parse_args()
if args.output.exists() or not 1 <= args.limit <= 200:
raise ValueError("New evidence directory and bounded frame count required")
args.output.mkdir(parents=True)
source = args.run / "camera/decisions.jsonl"
rows = [json.loads(line) for line in source.read_text().splitlines()]
rows = [r for r in rows if r["frame_id"] >= args.first_frame and r.get("goal")][: args.limit]
connection = http.client.HTTPConnection("127.0.0.1", 8010, timeout=5)
report = dict(
utc=dt.datetime.now(dt.UTC).isoformat(),
monotonic_ns=time.monotonic_ns(),
input_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
authority="offline-geometry-only-no-motion",
samples=[],
)
for row in rows:
frame = args.run / "camera" / f"{row['frame_id']:08d}.range.npz"
observation = np.load(frame)
payload = dict(
points=observation["points"].tolist(),
pose=observation["pose"].tolist(),
goal=row["goal"],
max_speed_mps=0.15,
body_contact_height_m=float(observation["body_contact_height_m"]),
include_terrain=row is rows[-1],
)
started = time.monotonic()
connection.request("POST", "/plan", body=json.dumps(payload))
response = connection.getresponse()
result = json.loads(response.read())
if response.status != 200:
raise RuntimeError(result)
terrain = result.pop("observed_terrain", None)
report["samples"].append(
dict(
frame=row["frame_id"],
result=result,
elapsed_ms=(time.monotonic() - started) * 1000,
source_sha256=hashlib.sha256(frame.read_bytes()).hexdigest(),
)
)
time.sleep(0.18)
connection.close()
if terrain is None:
raise RuntimeError("No matching terrain diagnostic returned")
terrain = np.asarray(terrain, dtype=np.float32)
np.save(args.output / "terrain.npy", terrain)
normalize = TerrainCostNormalizer()
profiler = cProfile.Profile()
profiler.enable()
result, count = normalize(terrain)
profiler.disable()
with (args.output / "profile.txt").open("w") as stream:
pstats.Stats(profiler, stream=stream).sort_stats("cumulative").print_stats(30)
timings = []
for _ in range(8):
started = time.monotonic()
repeated, repeated_count = normalize(terrain)
timings.append((time.monotonic() - started) * 1000)
assert np.array_equal(result, repeated) and repeated_count == count
report.update(
points=len(terrain),
corrected=count,
repeated_ms=timings,
completed_monotonic_ns=time.monotonic_ns(),
)
(args.output / "report.json").write_text(json.dumps(report, indent=2))
print(json.dumps(dict(points=len(terrain), corrected=count, repeated_ms=timings)))
if __name__ == "__main__":
main()
@@ -0,0 +1,100 @@
"""Conservative projective clearing at the declared range-image resolution.
All corners of a voxel must project inside one sensor's measured image. Every
sample covering that footprint must report free range beyond its farthest
corner. Invalid/self-occluded samples, image edges and depth discontinuities
cannot clear it. This removes surfaces, never creates ground observations.
"""
import itertools
import numpy as np
VIEW_FIELDS = ("view_models", "view_sizes", "view_axes", "view_parameters", "view_ranges")
class RangeImages:
def __init__(self, origins, packet):
self.origins = np.asarray(origins, dtype=float)
self.models = np.asarray(packet["view_models"])
self.sizes = np.asarray(packet["view_sizes"])
self.axes = np.asarray(packet["view_axes"], dtype=float)
self.parameters = np.asarray(packet["view_parameters"], dtype=float)
self.ranges = np.asarray(packet["view_ranges"], dtype=float)
n = len(self.models)
if (not 1 <= n <= 8 or self.models.shape != (n,)
or self.origins.shape != (n, 3) or self.sizes.shape != (n, 2)
or self.axes.shape != (n, 3, 3) or self.parameters.shape != (n, 4)
or not np.issubdtype(self.models.dtype, np.integer)
or not np.issubdtype(self.sizes.dtype, np.integer)
or not np.isin(self.models, [0, 1]).all()
or np.any(self.sizes < 2) or np.any(self.sizes > 4096)
or not all(np.isfinite(a).all() for a in
(self.origins, self.axes, self.parameters, self.ranges))
or not np.allclose(self.axes.transpose(0, 2, 1) @ self.axes,
np.eye(3), atol=1e-5)
or not np.allclose(np.linalg.det(self.axes), 1, atol=1e-5)):
raise ValueError("Invalid organized range calibration")
count = int(np.prod(self.sizes, axis=1).sum())
if (count > 8000 or self.ranges.shape != (count,)
or np.any(self.ranges < 0) or np.any(self.ranges > 8.01)):
raise ValueError("Invalid organized range samples")
for model, (w, h), p in zip(self.models, self.sizes, self.parameters, strict=True):
if model == 0:
if (p[1] <= 0 or p[3] <= 0 or abs(w*p[1]-360) > 1e-6
or p[2] <= -90 or p[2]+(h-1)*p[3] >= 90):
raise ValueError("Invalid spherical range calibration")
elif p[0] <= 0 or p[1] <= 0:
raise ValueError("Invalid pinhole range calibration")
def cleared(self, points, voxel_m, margin_m):
points = np.asarray(points, dtype=float).reshape(-1, 3)
result = np.zeros(len(points), dtype=bool)
if not len(points):
return result
offsets = np.asarray(list(itertools.product((0, 1), repeat=3))) * voxel_m
corners = np.floor(points[:, None, :] / voxel_m)*voxel_m + offsets
offset = 0
for model, (w, h), origin, axes, p in zip(
self.models, self.sizes, self.origins, self.axes, self.parameters, strict=True):
image = self.ranges[offset:offset+w*h].reshape(h, w)
offset += w*h
local = (corners-origin) @ axes
distance = np.linalg.norm(local, axis=2)
if model == 0:
u = (np.degrees(np.arctan2(local[..., 1], local[..., 0]))-p[0])/p[1]
# Unwrap each voxel locally across the azimuth image seam.
u = u[:, :1] + (u-u[:, :1]+w/2) % w-w/2
v = (np.degrees(np.arctan2(local[..., 2],
np.linalg.norm(local[..., :2], axis=2)))-p[2])/p[3]
visible = np.ones(len(points), dtype=bool)
else:
front = local[..., 0]
visible = (front > 1e-6).all(axis=1)
denominator = np.maximum(front, 1e-6)
u = p[2]-p[0]*local[..., 1]/denominator-0.5
v = p[3]-p[1]*local[..., 2]/denominator-0.5
low_u, high_u = np.floor(u.min(axis=1)), np.ceil(u.max(axis=1))
low_v, high_v = np.floor(v.min(axis=1)), np.ceil(v.max(axis=1))
visible &= (distance.min(axis=1) > margin_m) & (low_v >= 0) & (high_v < h)
if model == 1:
visible &= (low_u >= 0) & (high_u < w)
# A near-sensor voxel spanning a large portion of the image stays
# unknown. Bound work, without subsampling its clearing footprint.
visible &= (high_u-low_u <= 8) & (high_v-low_v <= 8) & ~result
indices = np.flatnonzero(visible)
if not len(indices):
continue
lu, hu = low_u[indices].astype(int), high_u[indices].astype(int)
lv, hv = low_v[indices].astype(int), high_v[indices].astype(int)
free = np.ones(len(indices), dtype=bool)
required = distance[indices].max(axis=1)+margin_m
for dv in range(int((hv-lv).max())+1):
for du in range(int((hu-lu).max())+1):
inside = (dv <= hv-lv) & (du <= hu-lu)
rows = np.flatnonzero(inside)
measured = image[lv[rows]+dv, (lu[rows]+du) % w]
free[rows] &= measured > required[rows]
result[indices[free]] = True
return result
@@ -0,0 +1,21 @@
"""Small bound observation receipt, including early body-goal rejections."""
import numpy as np
def route_observation(terrain, pose, value, max_step):
# Caller owns the same-stamp terrain/path/command transaction. This payload
# grants no motion and contains no scene truth; consumers must also match
# these candidates to the current range returns before excluding a route.
terrain = np.asarray(terrain)
obstacles = terrain[terrain[:, 3] > max_step + 1e-4]
order = np.argsort(np.linalg.norm(obstacles[:, :2] - pose[:2], axis=1), kind="stable")[:12]
return {
"schema_version": "missioncore.local-route-observation/v1",
"observation": {
"pose": list(pose),
"simulation_time_seconds": value.get("simulation_time_seconds"),
"execution_inputs_sha256": value["execution_inputs_sha256"],
},
"near_obstacles": obstacles[order].tolist(),
}
@@ -0,0 +1,133 @@
"""Bounded causal semantic barriers from observed calibrated range returns.
Applied AFTER geometric normalisation, so a smooth lawn cannot turn into a
permitted park path. Unknown cells retain geometry costs; no hidden scan/map
semantics are consulted. A reset destroys the entire memory with its ROS node.
"""
from collections import OrderedDict
import math
import numpy as np
class SemanticSurface:
# Preserve height: a wall/overhang must not relabel the floor beneath it.
# XY keeps the existing map resolution; Z matches the range voxel scale.
cell_size = np.array([0.2, 0.2, 0.06])
@classmethod
def cell_keys(cls, points):
return np.floor(np.asarray(points)[:, :3] / cls.cell_size).astype(int)
def __init__(self, *, retain_near=False, fuse_observations=False):
self.cells = OrderedDict()
self.retain_near = retain_near
self.position = None
self.fuse_observations = fuse_observations
self.evidence = {}
def retained(self, key, stamp, now):
return stamp >= now - 30 or (
self.retain_near
and self.position is not None
and math.hypot((key[0] + 0.5) * 0.2 - self.position[0],
(key[1] + 0.5) * 0.2 - self.position[1]) < 4.0
)
def observe(self, samples, now, pose=None, *, evidence_id=None):
evidence_id = now if evidence_id is None else evidence_id
if pose is not None:
position = np.asarray(pose, dtype=float)
if position.shape != (7,) or not np.isfinite(position).all():
raise ValueError("Invalid semantic memory pose")
self.position = position[:2].copy()
samples = np.asarray(samples, dtype=float)
if not samples.size:
return
if (
samples.ndim != 2
or samples.shape[1] != 4
or len(samples) > 30000
or not np.isfinite(samples).all()
or not np.isin(samples[:, 3], [0, 1]).all()
):
raise ValueError("Invalid observed semantic surface")
# Preserve measurement support inside each map cell. One excluded
# return still blocks a newly observed mixed cell, but is weaker
# contradictory evidence than an entire excluded surface patch.
cells = self.cell_keys(samples)
current = {}
for cell, permitted in zip(cells, samples[:, 3], strict=True):
key = tuple(cell)
count, excluded = current.get(key, (0, 0))
current[key] = (count + 1, excluded + int(not permitted))
for key, (count, excluded) in current.items():
permitted = int(excluded == 0)
if self.fuse_observations:
# Bounded binary evidence for the static surface layer. One
# misclassified pixel cannot erase repeated road observations.
# Range hazards remain immediate and independent. No calibrated
# probability is claimed for the model's binary confidence mask.
vote = -excluded / count if excluded else 1.0
previous = self.evidence.get(key)
if previous is None or not self.retained(key, self.cells[key][1], now):
base = 0
elif previous[1] == evidence_id:
base, vote = previous[2], min(previous[3], vote)
else:
base = previous[0]
score = max(-3, min(3, base + vote))
self.evidence[key] = (score, evidence_id, base, vote)
# Ties and first observations of exclusions are blocked.
permitted = int(score > 0)
self.cells[key] = (permitted, now)
self.cells.move_to_end(key)
for key, (_, stamp) in list(self.cells.items()):
if not self.retained(key, stamp, now):
del self.cells[key]
self.evidence.pop(key, None)
if len(self.cells) > 30000:
raise RuntimeError("Semantic memory capacity exceeded")
def apply(self, terrain, now):
result = terrain.copy()
cells = self.cell_keys(terrain)
# Nearby returns can share a voxel. Resolve its exact
# permission once, then map it back without changing expiry semantics.
unique, inverse = np.unique(cells, axis=0, return_inverse=True)
forbidden = np.array(
[
self.cells.get(tuple(c), (1, now))[0] == 0
and self.retained(tuple(c), self.cells[tuple(c)][1], now)
for c in unique
],
dtype=bool,
)[inverse]
result[forbidden, 3] = np.maximum(result[forbidden, 3], 1.0)
return result, int(forbidden.sum())
def permitted_terrain(self, terrain, now):
"""Positive surface evidence for a body-sized destination.
Obstacle absence is insufficient here: unknown and expired cells cannot
supply arrival support. Geometric obstacle costs remain intact.
"""
cells = self.cell_keys(terrain)
unique, inverse = np.unique(cells, axis=0, return_inverse=True)
allowed = np.array(
[
self.cells.get(tuple(c), (0, now))[0] == 1
and self.retained(tuple(c), self.cells[tuple(c)][1], now)
for c in unique
],
dtype=bool,
)[inverse]
return terrain[allowed]
def snapshot(self, now):
"""JSON-safe diagnostic evidence; does not refresh observation ages."""
return [
[int(key[0]), int(key[1]), int(key[2]), int(permitted), float(now - stamp)]
for key, (permitted, stamp) in self.cells.items()
]
+737 -42
View File
@@ -1,4 +1,4 @@
"""Bounded local HTTP adapter for the unchanged CMU ROS 2 navigation nodes.
"""Bounded local HTTP adapter for the pinned CMU ROS 2 navigation nodes.
Only simulated sensor observations enter ROS; no scene mesh or oracle route.
The container is owned by one episode. A reset restarts all causal ROS state.
@@ -13,32 +13,132 @@ import sys
import threading
import time
from collections import OrderedDict
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import numpy as np
import rclpy
from footprint import MAX_STEP_M, regulate_command
from geometry_msgs.msg import PointStamped, TwistStamped
from local_velocity_search import admit_forward_prefix
from arrival_approach import (
ArrivalApproach,
follower_stopped_short,
admit_path_alignment,
separate_counter_rotation,
terminal_path_command,
validate_orientation,
)
from footprint import Footprint
from command_status import command_failure
from detection_obstacles import DetectionObstacles
from geometry_msgs.msg import PointStamped, TwistStamped, PoseStamped
from continuous_control import ContinuousControl
from nav_msgs.msg import Odometry
from nav_msgs.msg import Path as RosPath
from observed_space import ObservedSpace
from rcl_interfaces.srv import SetParameters
from rclpy.node import Node
from rclpy.parameter import Parameter
from route_observation import route_observation
from semantic_surface import SemanticSurface
from sensor_msgs.msg import PointCloud2, PointField
from sensor_msgs_py import point_cloud2
from std_msgs.msg import Float32, Header
from support_policy import SupportPolicy
from terrain_costs import TerrainCostNormalizer, underbody_support_costs
from turn_staging import TurnStaging
from arrival_search import ArrivalPoseSearch
from support_obstacles import SupportObstacles
from observed_ground import observed_ground_costs
def execution_geometry():
path = os.environ.get("MISSIONCORE_RUN_INPUTS")
if path:
import hashlib
inputs = json.loads(Path(path).read_text())
body = {k: v for k, v in inputs.items() if k != "sha256"}
actual = hashlib.sha256(
json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
).hexdigest()
if (
inputs["schema_version"]
not in {
"missioncore.simulation-inputs/v1",
"missioncore.simulation-inputs/v2",
"missioncore.simulation-inputs/v3",
}
or actual != inputs["sha256"]
):
raise ValueError("Navigation execution inputs changed")
if (
inputs["schema_version"] == "missioncore.simulation-inputs/v1"
and "ground_contact" in inputs["robot"]["geometry"]
):
raise ValueError("Contact geometry requires execution inputs v2")
return (
inputs["robot"]["geometry"],
inputs["sha256"],
inputs["sensors"]["schema_version"]
in {"missioncore.simulation-sensor-rig/v2", "missioncore.simulation-sensor-rig/v3",
"missioncore.simulation-sensor-rig/v4"},
)
# Explicit compatibility for old lockstep/diagnostic callers only. Realtime
# requires the run identity in /ready and cannot silently use this branch.
legacy = Path(__file__).parents[1] / "robots/dcd006-v020.json"
return json.loads(legacy.read_text())["physics"], None, False
PROFILE, INPUTS_SHA256, MOUNTED_RIG = execution_geometry()
# Nodes normalize /speed by maxSpeed, so its envelope must also follow the run.
NAVIGATION_MAX_SPEED = max(1.0, float(json.loads(Path(os.environ["MISSIONCORE_RUN_INPUTS"]).read_text())["behavior"]["max_speed_mps"])) if INPUTS_SHA256 else 1.0
CONTINUOUS_RIG = bool(os.environ.get("MISSIONCORE_RUN_INPUTS") and
json.loads(Path(os.environ["MISSIONCORE_RUN_INPUTS"]).read_text())["sensors"]["schema_version"]
== "missioncore.simulation-sensor-rig/v4")
CONTINUOUS_BODY_TOP = PROFILE["height_m"]
if CONTINUOUS_RIG:
mounts = json.loads(Path(os.environ["MISSIONCORE_RUN_INPUTS"]).read_text())["sensors"]["mounts"]
CONTINUOUS_BODY_TOP = max(CONTINUOUS_BODY_TOP, *(
float(spec.get("body_center_m", spec.get("origin_m"))[2])
+ float(np.linalg.norm(spec["body_size_m"]))/2
for key, spec in mounts.items() if isinstance(spec, dict) and "body_size_m" in spec
))
MONITOR = Footprint(PROFILE)
DETECTIONS = DetectionObstacles(MONITOR)
SUPPORT_POLICY = SupportPolicy(MONITOR, observed_pivots=MOUNTED_RIG,
observed_approaches=CONTINUOUS_RIG, body_top_m=CONTINUOUS_BODY_TOP)
MAX_STEP_M = PROFILE["max_step_m"]
FOLLOWER_STOP_DISTANCE_M = 0.08
FOLLOWER_LOOKAHEAD_M = 0.7
def stamp_ns(stamp):
return stamp.sec * 1_000_000_000 + stamp.nanosec
def bind_maneuver(maneuver, pose, seconds):
if maneuver is None:
return None
return {
**maneuver,
"observation": {
"pose": pose.tolist(),
"simulation_time_seconds": seconds,
"execution_inputs_sha256": INPUTS_SHA256,
},
}
class Navigation(Node):
def __init__(self):
super().__init__("missioncore_navigation_adapter")
self.condition = threading.Condition()
self.plan_lock = threading.Lock()
self.seen_semantics = OrderedDict()
self.continuous_command = None
self.processes = []
self.path = self.command = self.terrain = None
self.terrain_geometry = None
self.odom = self.create_publisher(Odometry, "/state_estimation", 5)
self.scan = self.create_publisher(PointCloud2, "/registered_scan", 5)
self.goal = self.create_publisher(PointStamped, "/way_point", 5)
@@ -48,19 +148,52 @@ class Navigation(Node):
self.create_subscription(RosPath, "/path", self.on_path, 5)
self.create_subscription(TwistStamped, "/cmd_vel", self.on_command, 5)
self.create_subscription(PointCloud2, "/terrain_map_raw", self.on_terrain, 5)
if CONTINUOUS_RIG:
self.live_odom = self.create_publisher(Odometry, "/continuous_state", 1)
self.live_path = self.create_publisher(RosPath, "/continuous_path", 1)
self.create_subscription(TwistStamped, "/continuous_cmd_vel",
self.on_continuous_command, 1)
self.continuous = ContinuousControl(MONITOR, SUPPORT_POLICY,
self.publish_continuous_pose, self.publish_continuous_path,
lambda: self.continuous_command, body_top_m=CONTINUOUS_BODY_TOP)
self.slope_corrected = 0
self.terrain_processing_ms = 0.0
self.normalize_costs = TerrainCostNormalizer()
self.semantic_surface = SemanticSurface(retain_near=MOUNTED_RIG,
fuse_observations=CONTINUOUS_RIG)
self.observed_space = ObservedSpace()
self.support_poses = OrderedDict()
self.detection_observations = OrderedDict()
self.arrival_goal = None
# Search the complete mission acceptance region. Native braking is
# handled by the guarded terminal approach; only the measured pose
# and full-body support can actually satisfy the mission goal.
self.arrival_search = ArrivalPoseSearch()
# A measured support veto is a path constraint, not a soft preference:
# search must go around it before the track reaches the rejected patch.
# Use the same exclusion cost as semantics, so voxel aggregation does
# not dilute it back below the obstacle threshold. This search-only
# layer never changes physical geometry or the independent support fit.
self.support_obstacles = SupportObstacles(1.0)
self.terrain_search = None
self.arrival_approach = ArrivalApproach()
self.recovery_approach = ArrivalApproach()
self.turn_staging = TurnStaging(MONITOR)
self.motion_observation = None
self.underbody_corrected = 0
self.direction = False
self.direction_clients = [
self.create_client(SetParameters, f"/{name}/set_parameters")
for name in ("localPlanner", "pathFollower")
]
self.start_nodes()
def start_nodes(self):
common = dict(
autonomyMode=True,
autonomySpeed=0.3,
maxSpeed=1.0,
twoWayDrive=True,
maxSpeed=NAVIGATION_MAX_SPEED,
twoWayDrive=False,
joyToSpeedDelay=0.0,
)
configs = [
@@ -69,10 +202,12 @@ class Navigation(Node):
"terrainAnalysis",
dict(
scanVoxelSize=0.06,
# Keep the upstream near-field memory: an obstacle hidden
# by our own chassis must not disappear after one second.
decayTime=2.0,
noDecayDis=4.0,
# ObservedSpace owns memory. CMU replaces staging clouds
# per snapshot, without averaging old/fresh timestamps or
# resurrecting points removed by valid free rays.
inputIsMapSnapshot=True,
decayTime=0.5,
noDecayDis=0.0,
useSorting=True,
# Keep CMU's upstream ground quantile. Lower values make
# shallow scan depressions the reference for the entire
@@ -96,8 +231,14 @@ class Navigation(Node):
pathFolder="/opt/cmu/install/local_planner/share/local_planner/paths",
# Match the final monitor's 5 cm margin on every side;
# otherwise CMU repeatedly proposes a forbidden corner turn.
vehicleLength=1.1,
vehicleWidth=1.1,
vehicleLength=PROFILE["length_m"] + 0.1,
vehicleWidth=PROFILE["width_m"] + 0.1,
# Smooth obstacle cost across free space avoids choosing a
# route along the emergency-clearance boundary. Scale with
# the selected chassis; this is preference, not permission.
**({"footprintClearanceScale": PROFILE["width_m"] / 2,
"usePrefixGoalDirection": True}
if CONTINUOUS_RIG else {}),
useTerrainAnalysis=True,
checkObstacle=True,
# The pinned rectangular-filter image checks the complete
@@ -107,8 +248,8 @@ class Navigation(Node):
checkRotObstacle=False,
adjacentRange=5.0,
obstacleHeightThre=MAX_STEP_M,
groundHeightThre=0.08,
costHeightThre=0.08,
groundHeightThre=MAX_STEP_M * 0.8,
costHeightThre=MAX_STEP_M * 0.8,
useCost=True,
pointPerPathThre=1,
terrainVoxelSize=0.08,
@@ -136,7 +277,8 @@ class Navigation(Node):
"pathFollower",
dict(
**common,
lookAheadDis=0.7,
lookAheadDis=FOLLOWER_LOOKAHEAD_M,
**({"usePurePursuit": True} if CONTINUOUS_RIG else {}),
yawRateGain=2.0,
stopYawRateGain=2.0,
maxYawRate=20.0,
@@ -145,7 +287,7 @@ class Navigation(Node):
# The follower sees the cropped local prefix, not the
# mission endpoint. Do not stop before its 0.2 m minimum;
# waypoint arrival and the braking monitor remain separate.
stopDisThre=0.08,
stopDisThre=FOLLOWER_STOP_DISTANCE_M,
slowDwnDisThre=0.7,
useInclToStop=True,
inclThre=30.0,
@@ -162,6 +304,40 @@ class Navigation(Node):
for key, value in parameters.items():
args += ["-p", f"{key}:={str(value).lower() if isinstance(value, bool) else value}"]
self.processes.append(subprocess.Popen(args, start_new_session=True))
if CONTINUOUS_RIG and executable == "pathFollower":
follower = args + ["-r", "__node:=continuousFollower",
"-r", "/state_estimation:=/continuous_state",
"-r", "/path:=/continuous_path", "-r", "/cmd_vel:=/continuous_cmd_vel",
"-p", "pathInMapFrame:=true"]
self.processes.append(subprocess.Popen(follower, start_new_session=True))
def on_continuous_command(self, message):
self.continuous_command = (time.monotonic(), message.twist.linear.x,
message.twist.angular.z)
def publish_continuous_pose(self, pose):
odom = Odometry(header=Header(stamp=self.get_clock().now().to_msg(), frame_id="map"),
child_frame_id="vehicle")
odom.pose.pose.position.x, odom.pose.pose.position.y, odom.pose.pose.position.z = map(float, pose[:3])
q = odom.pose.pose.orientation
q.x, q.y, q.z, q.w = map(float, pose[3:])
self.live_odom.publish(odom)
def publish_continuous_path(self, points, pose):
pose = np.asarray(pose)
x, y, z, w = pose[3:]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
rotation = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
message = RosPath(header=Header(stamp=self.get_clock().now().to_msg(), frame_id="map"))
for point in points:
item = PoseStamped(header=message.header)
xy = np.asarray(point[:2]) @ rotation.T + pose[:2]
item.pose.position.x, item.pose.position.y = map(float, xy)
item.pose.position.z = float(pose[2])
item.pose.orientation.w = 1.0
message.poses.append(item)
self.live_path.publish(message)
def stop_nodes(self):
for process in self.processes:
@@ -177,12 +353,42 @@ class Navigation(Node):
def ready(self):
return (
len(self.processes) == 3
len(self.processes) == (4 if CONTINUOUS_RIG else 3)
and all(p.poll() is None for p in self.processes)
and self.odom.get_subscription_count() >= 3
and self.scan.get_subscription_count() >= 2
and all(client.service_is_ready() for client in self.direction_clients)
and (not CONTINUOUS_RIG or (
self.live_odom.get_subscription_count() >= 1
and self.live_path.get_subscription_count() >= 1
and self.count_publishers("/continuous_cmd_vel") >= 1
))
)
def set_direction(self, reverse):
if reverse == self.direction:
return
# Both nodes acknowledge the same permission before receiving this
# observation. Rejecting negative speed after primitive selection is
# too late: its preparatory turn can already point away from the goal.
request = SetParameters.Request(
parameters=[Parameter("twoWayDrive", value=reverse).to_parameter_msg()]
)
self.direction = None
futures = [client.call_async(request) for client in self.direction_clients]
completed = threading.Event()
for future in futures:
future.add_done_callback(lambda _: completed.set())
deadline = time.monotonic() + 0.5
while not all(future.done() for future in futures):
completed.wait(max(0, deadline - time.monotonic()))
completed.clear()
if time.monotonic() >= deadline:
raise RuntimeError("navigation direction was not acknowledged")
if not all(all(result.successful for result in f.result().results) for f in futures):
raise RuntimeError("navigation direction was rejected")
self.direction = reverse
def on_path(self, message):
with self.condition:
self.path = (
@@ -221,16 +427,41 @@ class Navigation(Node):
),
None,
)
detected = next((value for key, value in reversed(self.detection_observations.items())
if abs(key - stamp) <= 1000), np.empty((0, 3)))
underbody = 0
if support is not None:
points, underbody = underbody_support_costs(points, *support)
points, underbody = underbody_support_costs(points, *support, geometry=PROFILE)
if CONTINUOUS_RIG:
points, patches = observed_ground_costs(points, *support, monitor=MONITOR)
corrected += patches
with self.condition:
geometry = points.copy()
if CONTINUOUS_RIG:
if support is not None:
self.support_obstacles.revalidate(points, *support, monitor=MONITOR)
self.support_obstacles.observe_ahead(points, *support, monitor=MONITOR,
speed_mps=NAVIGATION_MAX_SPEED)
points = DETECTIONS.overlay(points, detected)
points, semantic_forbidden = self.semantic_surface.apply(points, time.monotonic())
# Search feedback must not become physical collision evidence or
# remove measured ground from the independent support assessment.
# Semantic exclusions and detected objects remain hard costs in
# BOTH layers. Bind any occupied-body hint exclusion to this exact
# stamped observation, never to an unrelated latest pose.
search_points = points
if CONTINUOUS_RIG:
search_points, _ = self.support_obstacles.apply(points,
pose=support[0] if support is not None else None, monitor=MONITOR)
fields = [
PointField(name=name, offset=i * 4, datatype=PointField.FLOAT32, count=1)
for i, name in enumerate(("x", "y", "z", "intensity"))
]
self.surface.publish(point_cloud2.create_cloud(message.header, fields, points))
self.surface.publish(point_cloud2.create_cloud(message.header, fields, search_points))
with self.condition:
self.terrain = (stamp_ns(message.header.stamp), len(points), points)
self.terrain_geometry = geometry
self.terrain_search = search_points
self.slope_corrected = corrected
self.underbody_corrected = underbody
self.terrain_processing_ms = (time.monotonic() - started) * 1000
@@ -244,6 +475,17 @@ class Navigation(Node):
goal = np.asarray(value["goal"], dtype=np.float64)
speed = float(value["max_speed_mps"])
reverse = value.get("allow_reverse", False)
arrival_target = value.get("arrival_target")
orientation = validate_orientation(value.get("orientation_target"))
recovery_orientation = value.get("recovery_orientation", False)
if type(recovery_orientation) is not bool:
raise ValueError("Invalid recovery orientation")
translation_allowed = value.get("translation_allowed", True)
goal_from_visual = value.get("visual_goal_available", False)
if type(goal_from_visual) is not bool:
raise ValueError("Invalid visual-goal provenance")
if type(translation_allowed) is not bool:
raise ValueError("Invalid translation permission")
contact_height = float(value.get("body_contact_height_m", 0.37))
if (
points.ndim != 2
@@ -251,7 +493,7 @@ class Navigation(Node):
or not 50 <= len(points) <= 30000
or pose.shape != (7,)
or goal.shape != (3,)
or not 0 <= speed <= 1
or not math.isfinite(speed) or not 0 <= speed <= NAVIGATION_MAX_SPEED
or not isinstance(reverse, bool)
or not math.isfinite(contact_height)
or not 0.1 <= contact_height <= 1.0
@@ -259,12 +501,105 @@ class Navigation(Node):
or abs(float(np.linalg.norm(pose[3:])) - 1) > 0.01
):
raise ValueError("invalid range/odometry contract")
detected = DETECTIONS.observed(value)
if value.get("detection_age_seconds", 0) > DETECTIONS.deadline_seconds:
return dict(speed_mps=0.0, yaw_rate_rps=0.0, status="blocked", path=[],
diagnostic={"failure": "stale-detection"})
original_orientation = orientation
simulation_time = float(value.get("simulation_time_seconds", 0))
if not math.isfinite(simulation_time) or simulation_time < 0:
raise ValueError("Invalid observation time")
stationary = False
if self.motion_observation is not None:
previous_pose, previous_time = self.motion_observation
dt = simulation_time - previous_time
stationary = (
0 < dt <= 0.8 and np.linalg.norm(pose[:2] - previous_pose[:2]) <= 0.025 * dt
)
self.motion_observation = (pose.copy(), simulation_time)
maneuver = (
self.turn_staging.current(pose, orientation, simulation_time) if MOUNTED_RIG else None
)
staging = maneuver is not None
if staging:
goal = np.asarray(maneuver["goal"])
orientation = {"key": orientation["key"] + "-stage", "xy": goal[:2].tolist()}
translation_allowed, arrival_target, reverse = True, None, False
speed = min(speed, 0.1)
goal_from_visual = False
if arrival_target is not None:
arrival_target = np.asarray(arrival_target, dtype=float)
simulation_time = float(value["simulation_time_seconds"])
if (
not math.isfinite(simulation_time)
or simulation_time < 0
or arrival_target.shape != (2,)
or not np.isfinite(arrival_target).all()
or np.linalg.norm(arrival_target - pose[:2]) > 3.5
):
raise ValueError("invalid arrival candidate")
if arrival_target is None:
self.arrival_goal = None
else:
if (
self.arrival_goal is not None
and self.arrival_goal["target_xy"] != arrival_target.tolist()
):
self.arrival_goal = None
if (
self.arrival_goal is not None
and self.arrival_goal.get("kind") == "observed-approach"
and np.linalg.norm(np.asarray(self.arrival_goal["goal"][:2]) - pose[:2])
<= 2 * FOLLOWER_STOP_DISTANCE_M
):
# Replan a short observed placement; its follower stop disk
# never stands in for the still-unreached mission target.
self.arrival_goal = None
# Once body-goal admission starts, visual intermediate goals cannot
# steer past the task region. Preserve its identity until completion
# or explicit rejection by a new observation.
if self.arrival_goal is not None:
goal = np.asarray(self.arrival_goal["goal"], dtype=float)
goal_from_visual = False
elif not goal_from_visual:
goal = np.array([*arrival_target, goal[2]])
self.set_direction(reverse)
memory_started = time.monotonic()
rays = value.get("range_rays") or {}
current_points = points
points = self.observed_space.observe(
points,
pose,
memory_started,
rays.get("origins"),
rays.get("ends"),
rays.get("origin_indices"),
range_views=rays,
)
memory_metrics = {
**self.observed_space.metrics,
"processing_ms": (time.monotonic() - memory_started) * 1000,
}
header = Header(stamp=self.get_clock().now().to_msg(), frame_id="map")
identity = stamp_ns(header.stamp)
with self.condition:
self.semantic_surface.observe(value.get("semantic_points", []), time.monotonic(), pose)
for sample in value.get("semantic_observations", []):
age = float(sample["age_seconds"])
if not math.isfinite(age) or age < 0:
raise ValueError("Invalid semantic capture age")
if sample["frame_id"] not in self.seen_semantics:
self.semantic_surface.observe(sample["samples"], time.monotonic()-age, pose,
evidence_id=sample.get("capture_id", sample["frame_id"]))
self.seen_semantics[sample["frame_id"]] = True
while len(self.seen_semantics) > 128:
self.seen_semantics.popitem(last=False)
self.support_poses[identity] = (pose.copy(), contact_height)
self.detection_observations[identity] = detected
while len(self.support_poses) > 8:
self.support_poses.popitem(last=False)
while len(self.detection_observations) > 8:
self.detection_observations.popitem(last=False)
odom = Odometry(header=header, child_frame_id="vehicle")
odom.pose.pose.position.x, odom.pose.pose.position.y, odom.pose.pose.position.z = map(
float, pose[:3]
@@ -309,6 +644,7 @@ class Navigation(Node):
"yaw_rate_rps": 0.0,
"status": "waiting-for-plan",
"path": [],
"maneuver": bind_maneuver(maneuver, pose, simulation_time),
"pending": {
"path_stamp_delta_ns": None
if self.path is None
@@ -330,35 +666,316 @@ class Navigation(Node):
),
}
path, command = self.path, self.command
route_evidence = route_observation(self.terrain[2], pose, value, MAX_STEP_M)
if staging and not self.turn_staging.confirm_surface(
self.terrain[2],
self.semantic_surface.permitted_terrain(self.terrain[2], time.monotonic()),
pose,
contact_height,
):
return {
"speed_mps": 0.0,
"yaw_rate_rps": 0.0,
"status": "waiting-for-plan",
"path": [],
"route_observation": route_evidence,
"maneuver": bind_maneuver(self.turn_staging.active, pose, simulation_time),
"diagnostic": {
"failure": self.turn_staging.transition
if self.turn_staging.active is None
else "turn-placement-needs-surface-view",
"placement_hazards": [
{
"point": point.tolist(),
"geometry_cost": float(geometry[3]),
"semantic_cell": self.semantic_surface.cells.get(
tuple(self.semantic_surface.cell_keys(point[None])[0])
),
}
for point, geometry in zip(
self.terrain[2], self.terrain_geometry, strict=True
)
if point[3] > MAX_STEP_M + 1e-4
and np.linalg.norm(point[:2] - np.asarray(maneuver["goal"][:2])) < 0.8
][:16],
},
}
valid = len(path[2]) > 1 and all(math.isfinite(v) for v in command[2:])
velocity = max(-speed, min(speed, command[2]))
velocity = max(-speed, min(speed, command[2])) if valid else 0.0
yaw_rate = command[3] if valid else 0.0
orientation_controller = self.recovery_approach if recovery_orientation else self.arrival_approach
velocity, yaw_rate, approach = orientation_controller.command(
pose,
orientation,
float(value.get("simulation_time_seconds", 0)),
velocity,
yaw_rate,
enabled=not reverse,
)
orienting = approach["phase"] in {"braking", "aligning"}
# A pivot can acquire a view before a path exists. It has zero
# translation and still needs the full sensor-based sweep below.
valid = orienting or (valid and translation_allowed)
arrival = None
terminal_proposal = None
destination_pending = False
if arrival_target is not None and not orienting:
# Completion within an entered task region requires geometric
# support and retains all known semantic barriers. Acquiring a
# blind-strip destination outside it also requires positive
# semantic evidence over all selected ground contact patches.
# Chassis collision clearance remains independent and full-body.
inside_arrival = np.linalg.norm(arrival_target - pose[:2]) <= 0.4
support = (
None
if inside_arrival
else self.semantic_surface.permitted_terrain(self.terrain[2], time.monotonic())
)
arrival = MONITOR.assess_pose(
self.terrain[2], pose, contact_height, support_terrain=support
)
arrival["observation"] = {
"pose": pose.tolist(),
"target_xy": arrival_target.tolist(),
"simulation_time_seconds": simulation_time,
"execution_inputs_sha256": value["execution_inputs_sha256"],
}
# Assessment uses this transaction's terrain and exact pose;
# a point inside the arrival circle cannot bypass the body.
arrival["positive_surface_required"] = not inside_arrival
if arrival["admitted"] and inside_arrival:
return {
"speed_mps": 0.0,
"yaw_rate_rps": 0.0,
"status": "arrival-accepted",
"route_observation": route_evidence,
"path": [],
"arrival": arrival,
}
# Keep approaching only an observed body-sized destination.
# This guard grants no route: the existing swept command and
# direction checks must still admit every actual command.
destination = pose.copy()
destination[:2] = goal[:2]
# Goal Z is observed ground; retain the measured body attitude.
up_z = 1 - 2 * (pose[3] ** 2 + pose[4] ** 2)
destination[2] = goal[2] + contact_height / max(up_z, 0.1)
arrival["destination"] = MONITOR.assess_pose(
self.terrain[2], destination, contact_height, support_terrain=support
)
if valid and arrival["destination"]["admitted"]:
terminal_proposal = terminal_path_command(
pose,
goal,
path[2],
command[2:],
stop_distance=FOLLOWER_STOP_DISTANCE_M,
maximum_speed=speed,
command_bounds=MONITOR.command_bounds,
)
# CMU stops within a disk around its target. A supported target
# does not certify the different measured pose in that disk.
# If it holds there without body admission, select another
# observed destination outside the old stopping disk. Keep the
# same mission region and finite recovery/progress budget.
follower_at_goal = terminal_proposal is None and follower_stopped_short(
pose,
goal,
command[2:],
arrival_complete=arrival["admitted"] and inside_arrival,
stop_distance=FOLLOWER_STOP_DISTANCE_M,
)
if not arrival["destination"]["admitted"] or follower_at_goal:
candidate = MONITOR.find_arrival_pose(
self.terrain[2],
pose,
arrival_target,
contact_height,
support_terrain=support,
minimum_translation_m=2 * FOLLOWER_STOP_DISTANCE_M
if follower_at_goal
else 0.0,
refinement=self.arrival_search,
)
intermediate = False
if candidate is None and MOUNTED_RIG and not inside_arrival and not reverse:
candidate = MONITOR.find_observed_approach(
self.terrain[2],
pose,
arrival_target,
contact_height,
support_terrain=support,
minimum_translation_m=2 * FOLLOWER_STOP_DISTANCE_M,
)
intermediate = candidate is not None
self.arrival_goal = None
if candidate is not None:
candidate_up_z = 1 - 2 * (candidate[3] ** 2 + candidate[4] ** 2)
self.arrival_goal = {
"target_xy": arrival_target.tolist(),
"goal": [
*candidate[:2],
candidate[2] - contact_height / candidate_up_z,
],
**({"kind": "observed-approach"} if intermediate else {}),
}
# A distant stopping footprint is not the current command
# sweep. An unchanged visual goal may retain its freshly
# computed local prefix while destination admission is
# pending. It receives NO body receipt or new capture age;
# every existing sweep/fresh-track/unknown limit below and
# the visual intent deadman still apply. Inside the actual
# task region only the full body admission can complete it.
destination_pending = bool(
candidate is None
and MOUNTED_RIG
and goal_from_visual
and valid
and not inside_arrival
and not reverse
and not follower_at_goal
)
if candidate is None and not destination_pending and MOUNTED_RIG and stationary:
maneuver = self.turn_staging.propose(
self.terrain[2],
None,
pose,
original_orientation,
simulation_time,
contact_height,
)
if not destination_pending:
return {
"speed_mps": 0.0,
"yaw_rate_rps": 0.0,
"status": "waiting-for-plan" if candidate is not None else "blocked",
"route_observation": route_evidence,
"path": [],
"arrival": arrival,
"arrival_goal": self.arrival_goal,
"maneuver": bind_maneuver(maneuver, pose, simulation_time),
"diagnostic": {
"failure": "goal-body-support",
"follower_at_goal": bool(follower_at_goal),
"turn_placement_candidates": self.turn_staging.candidates
if MOUNTED_RIG
else [],
},
}
if not destination_pending:
self.arrival_goal = {
"target_xy": arrival_target.tolist(),
"goal": goal.tolist(),
**(
{"kind": "observed-approach"}
if self.arrival_goal is not None
and self.arrival_goal.get("kind") == "observed-approach"
else {}
),
}
if (staging and valid and not orienting
and maneuver.get("positive_surface_admitted")):
# A turn placement has the same native stopping disk as a
# mission destination. Stopping short must not strand the body
# before the measured pose can admit its turn. confirm_surface
# already rechecked the complete destination this transaction;
# the terminal proposal still needs every live sweep gate.
terminal_proposal = terminal_path_command(
pose, goal, path[2], command[2:],
stop_distance=FOLLOWER_STOP_DISTANCE_M,
maximum_speed=speed, command_bounds=MONITOR.command_bounds,
)
if terminal_proposal is not None:
velocity, yaw_rate, _ = terminal_proposal
local_turn = None
if MOUNTED_RIG and MONITOR.contacts is not None and not reverse:
velocity, yaw_rate, local_turn = separate_counter_rotation(
velocity,
yaw_rate,
[(low[1] + high[1]) / 2 for low, high in MONITOR.contacts.bands],
stationary=stationary,
)
local_pivot = local_turn is not None or (abs(velocity) < 1e-8 and abs(yaw_rate) > 1e-8)
if MOUNTED_RIG and abs(velocity) < 1e-8 and abs(yaw_rate) > 1e-8:
limit = SUPPORT_POLICY.partial_yaw_rps
yaw_rate = max(-limit, min(limit, yaw_rate)) if stationary else 0.0
# Reverse is admitted only by the composed recovery policy after
# observing full-width support. Bound heading changes to that strip.
direction_clear = (
velocity <= 0 and abs(command[3]) <= 0.15 if reverse else velocity >= 0
)
direction_clear = velocity <= 0 and abs(yaw_rate) <= 0.15 if reverse else velocity >= 0
velocity, yaw_rate, command_scale = (
regulate_command(velocity, command[3], self.terrain[2], pose)
MONITOR.regulate_command(velocity, yaw_rate, self.terrain[2], pose)
if valid and direction_clear
else (0.0, 0.0, 0.0)
)
footprint_clear = command_scale > 0
valid = valid and footprint_clear and direction_clear
# Assess the actual obstacle-regulated command. Fresh returns are
# kept separate from causal memory: old ground cannot excuse loss
# of current view. Unknown cells remain unknown after regulation.
velocity, yaw_rate, support_scale, motion_support = SUPPORT_POLICY.regulate(
velocity,
yaw_rate,
self.terrain[2],
pose,
contact_height,
current_points=current_points,
)
if (CONTINUOUS_RIG and valid and direction_clear
and (command_scale == 0 or support_scale == 0)):
alignment = admit_path_alignment(
path[2], MONITOR, SUPPORT_POLICY, self.terrain[2], pose,
contact_height, current_points, stationary=stationary,
reverse=reverse, orienting=orienting, lookahead_m=FOLLOWER_LOOKAHEAD_M)
if alignment is not None:
velocity, yaw_rate, command_scale, support_scale, motion_support, detail = alignment
approach = {**approach, **detail}
footprint_clear, local_pivot = True, True
if (CONTINUOUS_RIG and valid and translation_allowed
and (command_scale == 0 or support_scale == 0 or (local_pivot and not stationary))
and not orienting and not reverse):
forward = admit_forward_prefix(path[2], MONITOR, SUPPORT_POLICY,
self.terrain[2], pose, contact_height, current_points,
lookahead_m=FOLLOWER_LOOKAHEAD_M, maximum_speed=speed)
if forward is not None:
velocity, yaw_rate, command_scale, support_scale, motion_support, local_turn = forward
footprint_clear, direction_clear = True, True
motion_support["observation"] = {
"pose": pose.tolist(),
"simulation_time_seconds": value.get("simulation_time_seconds"),
"execution_inputs_sha256": value["execution_inputs_sha256"],
}
if CONTINUOUS_RIG:
# Keep this transaction's veto. On the next observation CMU
# sees measured non-traversable patches as costs and can choose a
# different primitive instead of repeating the rejected arc.
self.support_obstacles.observe(
motion_support.get("roughness_obstacles_xyz", []), self.terrain[2])
self.support_obstacles.observe_patches(
motion_support.get("support_obstacle_samples", []), self.terrain[2])
velocity, yaw_rate, detection_scale = DETECTIONS.regulate(
velocity, yaw_rate, detected, pose)
valid = (valid and footprint_clear and direction_clear
and support_scale > 0 and detection_scale > 0)
qx, qy, qz, qw = pose[3:]
tilt = math.degrees(math.acos(max(-1, min(1, 1 - 2 * (qx * qx + qy * qy)))))
failure = (
"inclination"
if tilt >= 30
else "no-path"
if len(path[2]) <= 1
else "footprint"
if not footprint_clear
else "direction"
if not direction_clear
else "controller-hold"
if abs(command[2]) + abs(command[3]) < 1e-5
else "none"
failure = command_failure(
tilt=tilt, orienting=orienting, translation_allowed=translation_allowed,
path_points=len(path[2]), footprint_clear=footprint_clear,
direction_clear=direction_clear, support_scale=support_scale,
support_reason=motion_support["policy"]["reason"],
velocity=velocity, yaw_rate=yaw_rate,
)
if detection_scale == 0 and failure in {"none", "controller-hold"}:
failure = "detected-object-sweep"
if MOUNTED_RIG and not staging and orienting and support_scale == 0 and stationary:
maneuver = self.turn_staging.propose(
self.terrain[2],
None,
pose,
original_orientation,
simulation_time,
contact_height,
)
maneuver = bind_maneuver(maneuver, pose, simulation_time)
obstacles = self.terrain[2][self.terrain[2][:, 3] > MAX_STEP_M]
distances = np.linalg.norm(obstacles[:, :2] - pose[:2], axis=1)
near = obstacles[np.argsort(distances)[:12]]
@@ -366,19 +983,40 @@ class Navigation(Node):
"speed_mps": velocity if valid else 0.0,
"yaw_rate_rps": max(-0.8, min(0.8, yaw_rate)) if valid else 0.0,
"status": "path" if valid else "blocked",
"path": path[2][::3],
"route_observation": route_evidence,
# This path also feeds the independent live follower. Dropping
# samples here (especially the endpoint) changes its stopping
# distance and curvature relative to the planning follower.
"path": path[2],
"terrain_points": self.terrain[1],
"maneuver": maneuver,
"footprint_clear": bool(footprint_clear),
"path_frame": "vehicle-yaw",
**(
{"arrival": arrival, "arrival_goal": self.arrival_goal}
if arrival is not None
else {}
),
"diagnostic": {
"failure": failure,
"tilt_degrees": tilt,
"controller_command": list(command[2:]),
"arrival_approach": approach,
"local_turn": local_turn,
"terminal_approach": terminal_proposal[2] if terminal_proposal else None,
"destination_admission_pending": destination_pending,
"near_obstacles": near.tolist(),
"slope_corrected_points": self.slope_corrected,
"underbody_support_points": self.underbody_corrected,
"terrain_processing_ms": self.terrain_processing_ms,
"command_scale": command_scale,
"detected_object_points": len(detected),
"detection_command_scale": detection_scale,
"motion_support": motion_support,
"range_memory": memory_metrics,
"turn_placement_candidates": self.turn_staging.candidates
if MOUNTED_RIG
else [],
},
# Engineering replay only; this local endpoint never forwards
# dense geometry to the operator or changes the control input.
@@ -400,6 +1038,10 @@ def main():
thread.start()
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
# Tiny control replies must not wait for delayed ACK between their
# headers and JSON body. Each connection remains keep-alive and bounded.
disable_nagle_algorithm = True
def reply(self, status, value):
body = json.dumps(value, allow_nan=False).encode()
self.send_response(status)
@@ -409,8 +1051,27 @@ def main():
self.wfile.write(body)
def do_GET(self):
if self.path == "/diagnostic-snapshot" and CONTINUOUS_RIG:
# Read-only, bounded to the latest transaction. Never insert
# diagnostic material back into the causal observation stream.
with node.plan_lock:
exchange = node.continuous.snapshot()
with node.condition:
geometry = (node.terrain_geometry.tolist()
if node.terrain_geometry is not None else [])
search = (node.terrain_search.tolist()
if node.terrain_search is not None else [])
self.reply(200, dict(schema_version="missioncore.navigation-diagnostic/v1",
authority="none", execution_inputs_sha256=INPUTS_SHA256,
exchange=exchange, geometry=geometry, search=search))
return
self.reply(
200 if self.path == "/ready" and node.ready() else 503, {"ready": node.ready()}
200 if self.path == "/ready" and node.ready() else 503,
{
"ready": node.ready(),
"execution_inputs_sha256": INPUTS_SHA256,
"robot_geometry": PROFILE,
},
)
def do_POST(self):
@@ -427,7 +1088,41 @@ def main():
# all cached graph/history state before the next observation.
os.execv(sys.executable, [sys.executable, str(Path(__file__).resolve())])
elif self.path == "/plan":
self.reply(200, node.plan(value))
if value.get("execution_inputs_sha256") != INPUTS_SHA256:
raise ValueError("Navigation execution input identity mismatch")
with node.plan_lock:
if value.get("continuous"):
if not CONTINUOUS_RIG:
raise ValueError("Continuous input requires the v4 rig")
node.continuous.observe(value)
result = node.plan(value)
if value.get("continuous"):
node.continuous.accept(value, result,
node.terrain[2] if node.terrain is not None else [])
# Bounded engineering snapshots must also cover rejected
# arrivals. Successful-path-only traces hid the terrain
# responsible for a stop. Never expose these in the UI or
# feed them back into the observation stream.
if value.get("include_terrain") is True:
with node.condition:
if node.terrain is not None:
now = time.monotonic()
result["observation_debug"] = {
"terrain_stamp_ns": node.terrain[0],
"geometry": node.terrain_geometry.tolist(),
"terrain": node.terrain[2].tolist(),
"permitted": node.semantic_surface.permitted_terrain(
node.terrain[2], now
).tolist(),
"semantic_cells": node.semantic_surface.snapshot(now),
"semantic_cell_size_m": node.semantic_surface.cell_size.tolist(),
"semantic_cell_columns": ["x", "y", "z", "permitted", "age_seconds"],
}
self.reply(200, result)
elif self.path == "/control" and CONTINUOUS_RIG:
if value.get("execution_inputs_sha256") != INPUTS_SHA256:
raise ValueError("Continuous execution identity mismatch")
self.reply(200, node.continuous.tick(value))
else:
self.reply(404, {"error": "unknown endpoint"})
except (ValueError, KeyError, TypeError) as exc:
@@ -439,7 +1134,7 @@ def main():
pass
try:
HTTPServer(("0.0.0.0", 8010), Handler).serve_forever()
ThreadingHTTPServer(("0.0.0.0", 8010), Handler).serve_forever()
finally:
node.stop_nodes()
rclpy.shutdown()
@@ -0,0 +1,168 @@
// Exact observed-patch and swept-contact hot loops. No scene/map identities,
// extrapolation, temporal cache, or changed admission thresholds.
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <deque>
#include <map>
#include <vector>
using Point = std::array<double,3>;
using Key = std::pair<int64_t,int64_t>;
struct Surface {
std::vector<Point> ground;
std::map<Key,std::vector<int>> buckets;
std::map<std::pair<double,double>,int> results;
double radius, contact, step, slope;
std::array<double,3> up;
std::vector<uint8_t> connected;
bool referenced;
Surface(const double* p,int n,double r,double h,double s,double m,const double* u,double anchor=0,
const double* reference=nullptr,int reference_n=0)
:radius(r),contact(h),step(s),slope(m),up{u[0],u[1],u[2]},referenced(reference_n>0) {
for(int i=0;i<n;i++) {
ground.push_back({p[3*i],p[3*i+1],p[3*i+2]});
buckets[key(p[3*i],p[3*i+1])].push_back(i);
}
auto graph_buckets=buckets;
for(int i=0;i<reference_n;i++) {
ground.push_back({reference[3*i],reference[3*i+1],reference[3*i+2]});
graph_buckets[key(reference[3*i],reference[3*i+1])].push_back(n+i);
}
n+=reference_n;
connected.resize(n,0);
if(anchor<=0 || up[2]<=0) return;
std::deque<int> pending;
for(int i=0;i<n;i++) {
auto p=ground[i];
double expected=(-contact-up[0]*p[0]-up[1]*p[1])/up[2];
if(std::hypot(p[0],p[1])<=anchor && std::abs(p[2]-expected)<=step+1e-4) {
connected[i]=1;pending.push_back(i);
}
}
while(!pending.empty()) {
int i=pending.front();pending.pop_front();auto p=ground[i];auto k=key(p[0],p[1]);
for(int dx=-1;dx<=1;dx++) for(int dy=-1;dy<=1;dy++) {
auto found=graph_buckets.find({k.first+dx,k.second+dy});
if(found==graph_buckets.end()) continue;
for(int j:found->second) if(!connected[j]) {
auto q=ground[j];double x=p[0]-q[0],y=p[1]-q[1];
if(x*x+y*y<=.12*.12 && std::abs(p[2]-q[2])<=step+1e-4) {
connected[j]=1;pending.push_back(j);
}
}
}
}
}
Key key(double x,double y) const { return {int64_t(std::floor(x/radius)),int64_t(std::floor(y/radius))}; }
int classify(double x,double y,uint8_t* raised) const {
const auto k=key(x,y);
std::vector<int> near;
for(int dx=-1;dx<=1;dx++) for(int dy=-1;dy<=1;dy++) {
auto b=buckets.find({k.first+dx,k.second+dy});
if(b==buckets.end()) continue;
for(int i:b->second) {
const auto& p=ground[i];double a=p[0]-x,b=p[1]-y;
if(a*a+b*b<=radius*radius) near.push_back(i);
}
}
if(near.size()<3) return 0; // insufficient returns
std::sort(near.begin(),near.end());
double mx=0,my=0,mz=0,closest=1e100;
std::vector<double> angles;
for(int i:near) {auto p=ground[i];double a=p[0]-x,b=p[1]-y;
mx+=a;my+=b;mz+=p[2];closest=std::min(closest,a*a+b*b);
angles.push_back(std::atan2(b,a));}
const double n=near.size();mx/=n;my/=n;mz/=n;
double xx=0,xy=0,yy=0,xz=0,yz=0;
for(int i:near) {auto p=ground[i];double a=p[0]-x-mx,b=p[1]-y-my,z=p[2]-mz;
xx+=a*a;xy+=a*b;yy+=b*b;xz+=a*z;yz+=b*z;}
if((xx+yy-std::hypot(xx-yy,2*xy))/(2*(n-1))<1e-5) return 1;
std::sort(angles.begin(),angles.end());
double gap=angles.front()+2*std::acos(-1)-angles.back();
for(size_t i=1;i<angles.size();i++) gap=std::max(gap,angles[i]-angles[i-1]);
if(closest>1e-12 && gap>std::acos(-1)+1e-6) return 2;
if(up[2]<=0) return 3;
const double det=xx*yy-xy*xy;
const double a=(xz*yy-yz*xy)/det,b=(yz*xx-xz*xy)/det,c=mz-a*mx-b*my;
if(std::hypot(a,b)>slope+1e-4) return 4;
bool anchored=std::all_of(near.begin(),near.end(),[&](int i){return connected[i]!=0;});
if(!anchored && std::abs(c-(-contact-up[0]*x-up[1]*y)/up[2])>step+1e-4) return 5;
// A graph route around a ledge cannot authorize crossing that ledge.
for(size_t i=0;i<near.size();i++) for(size_t j=i+1;j<near.size();j++) {
auto p=ground[near[i]],q=ground[near[j]];double dx=p[0]-q[0],dy=p[1]-q[1];
if(dx*dx+dy*dy<=.12*.12 && std::abs(p[2]-q[2])>step+1e-4) return 5;
}
double residual=0;
for(int i:near) {auto p=ground[i];residual=std::max(residual,std::abs(p[2]-a*(p[0]-x)-b*(p[1]-y)-c));}
if(residual>0.05) {
for(int i:near) {auto p=ground[i];if(p[2]-a*(p[0]-x)-b*(p[1]-y)-c>0.05) raised[i]=1;}
return 6;
}
return referenced && !anchored ? 8 : 7; // measured patch needs a height anchor
}
};
extern "C" void* support_create(const double* p,int n,double r,double h,double s,double m,const double* u) {
try{return new Surface(p,n,r,h,s,m,u);}catch(...){return nullptr;}
}
extern "C" void* support_create_connected(const double* p,int n,double r,double h,double s,double m,const double* u,double anchor) {
try{return new Surface(p,n,r,h,s,m,u,anchor);}catch(...){return nullptr;}
}
extern "C" void* support_create_referenced(const double* p,int n,double r,double h,double s,double m,const double* u,double anchor,const double* reference,int reference_n) {
try{return new Surface(p,n,r,h,s,m,u,anchor,reference,reference_n);}catch(...){return nullptr;}
}
extern "C" void support_destroy(void* h) {delete static_cast<Surface*>(h);}
extern "C" int support_classify(void* h,const double* q,int n,int32_t* reasons,uint8_t* raised) {
try{if(!h)return -1;auto s=static_cast<Surface*>(h);
for(int i=0;i<n;i++) {
const auto key=std::make_pair(q[2*i],q[2*i+1]);
auto cached=s->results.find(key);
if(cached!=s->results.end()) reasons[i]=cached->second;
else {reasons[i]=s->classify(key.first,key.second,raised);s->results[key]=reasons[i];}
}
return n;}catch(...){return -1;}
}
struct Patch {int side;double x,y,c,s;std::array<double,4> extent;};
extern "C" int contact_cells(const double* low,const double* high,double yaw,double horizon,
const double* bands,double* cells,uint8_t* sides) {
try {
constexpr double spacing=.05,angle_step=.05;
double span=std::abs(yaw)*horizon;
if(!std::isfinite(span)||span>256*angle_step)return -2;
int count=int(std::ceil(span/angle_step));
double tx=(low[0]+high[0])/2,ty=(low[1]+high[1])/2;
double rx=(high[0]-low[0])/2,ry=(high[1]-low[1])/2;
std::vector<Patch> patches;
double xmin=1e100,ymin=1e100,xmax=-1e100,ymax=-1e100;
for(int side=0;side<2;side++) {
const double* b=bands+4*side;
double cx=(b[0]+b[2])/2,cy=(b[1]+b[3])/2,hx=(b[2]-b[0])/2,hy=(b[3]-b[1])/2;
double reach=std::hypot(std::max(std::abs(b[0]),std::abs(b[2])),std::max(std::abs(b[1]),std::abs(b[3])));
double pad=spacing/std::sqrt(2.)+(count?reach*angle_step/2:0);
for(int i=0;i<std::max(1,count);i++) {
double theta=count?std::copysign((i+.5)*angle_step,yaw):0,c=std::cos(theta),s=std::sin(theta);
Patch p{side,tx+c*cx-s*cy,ty+s*cx+c*cy,c,s,
{std::abs(c)*hx+std::abs(s)*hy+rx+pad,
std::abs(s)*hx+std::abs(c)*hy+ry+pad,
hx+std::abs(c)*rx+std::abs(s)*ry+pad,
hy+std::abs(s)*rx+std::abs(c)*ry+pad}};
xmin=std::min(xmin,p.x-p.extent[0]);xmax=std::max(xmax,p.x+p.extent[0]);
ymin=std::min(ymin,p.y-p.extent[1]);ymax=std::max(ymax,p.y+p.extent[1]);patches.push_back(p);
}
}
double ax=std::floor(xmin/spacing),ay=std::floor(ymin/spacing),bx=std::ceil(xmax/spacing),by=std::ceil(ymax/spacing);
if(!std::isfinite(ax+ay+bx+by)||(bx-ax+1)*(by-ay+1)>20000||std::max({std::abs(ax),std::abs(ay),std::abs(bx),std::abs(by)})>1e8)return -2;
int n=0;
for(int x=int(ax);x<=int(bx);x++)for(int y=int(ay);y<=int(by);y++) {
bool hit[2]={false,false};
for(const auto& p:patches) {
if(hit[p.side])continue;
double dx=x*spacing-p.x,dy=y*spacing-p.y;
if(std::abs(dx)<=p.extent[0]+1e-10&&std::abs(dy)<=p.extent[1]+1e-10&&
std::abs(dx*p.c+dy*p.s)<=p.extent[2]+1e-10&&std::abs(-dx*p.s+dy*p.c)<=p.extent[3]+1e-10)hit[p.side]=true;
}
if(hit[0]||hit[1]){cells[2*n]=x*spacing;cells[2*n+1]=y*spacing;sides[2*n]=hit[0];sides[2*n+1]=hit[1];n++;}
}
return n;
} catch(...){return -1;}
}
@@ -0,0 +1,63 @@
"""Optional exact CPU kernels; the NumPy reference remains portable and testable."""
import ctypes
import weakref
from pathlib import Path
import numpy as np
def load_library(path):
library = ctypes.CDLL(str(path))
array = np.ctypeslib.ndpointer(dtype=np.float64, flags="C_CONTIGUOUS")
integer = np.ctypeslib.ndpointer(dtype=np.int32, flags="C_CONTIGUOUS")
byte = np.ctypeslib.ndpointer(dtype=np.uint8, flags="C_CONTIGUOUS")
library.support_create_referenced.argtypes = [array, ctypes.c_int, *([ctypes.c_double] * 4), array, ctypes.c_double, array, ctypes.c_int]
library.support_create_referenced.restype = ctypes.c_void_p
library.support_destroy.argtypes = [ctypes.c_void_p]
library.support_destroy.restype = None
library.support_classify.argtypes = [ctypes.c_void_p, array, ctypes.c_int, integer, byte]
library.support_classify.restype = ctypes.c_int
library.contact_cells.argtypes = [array, array, ctypes.c_double, ctypes.c_double, array, array, byte]
library.contact_cells.restype = ctypes.c_int
return library
PATH = Path("/opt/missioncore/libsupport_surface.so")
LIBRARY = load_library(PATH) if PATH.is_file() else None
REASONS = np.array(["insufficient-returns", "collinear-returns", "outside-observed-patch",
"body-attitude", "slope", "height-discontinuity", "roughness", "observed-patch", "unanchored-ground"])
STATES = np.array(["unknown", "unknown", "unknown", "observed-unsafe", "observed-unsafe",
"observed-unsafe", "observed-unsafe", "observed-supported", "unknown"])
class NativeSurface:
def __init__(self, surface):
self.library = LIBRARY
self.ground = np.ascontiguousarray(surface.ground, dtype=np.float64)
self.handle = self.library.support_create_referenced(self.ground, len(self.ground), surface.radius_m,
surface.contact_height, surface.max_step, surface.max_slope, np.ascontiguousarray(surface.up), surface.anchor_radius,
np.ascontiguousarray(surface.continuity), len(surface.continuity))
if not self.handle:
raise RuntimeError("Support kernel allocation failed")
self.finalizer = weakref.finalize(self, self.library.support_destroy, self.handle)
def classify(self, offsets):
offsets = np.ascontiguousarray(offsets, dtype=np.float64)
reasons = np.empty(len(offsets), dtype=np.int32)
raised = np.zeros(len(self.ground), dtype=np.uint8)
if self.library.support_classify(self.handle, offsets, len(offsets), reasons, raised) != len(offsets):
raise RuntimeError("Support kernel failed")
return STATES[reasons], REASONS[reasons], self.ground[raised.astype(bool)]
def contact_cells(bands, bounds, yaw_rate):
cells = np.empty((20000, 2), dtype=np.float64)
sides = np.empty((20000, 2), dtype=np.uint8)
low = np.array(bounds["centre_lower_xy_m"]) - bounds["discrepancy_xy_m"]
high = np.array(bounds["centre_upper_xy_m"]) + bounds["discrepancy_xy_m"]
n = LIBRARY.contact_cells(np.ascontiguousarray(low), np.ascontiguousarray(high), yaw_rate,
bounds["horizon_seconds"], np.ascontiguousarray(bands, dtype=np.float64), cells, sides)
if n == -2:
raise ValueError("Contact sweep exceeds bounded sample budget")
if not 0 <= n <= len(cells):
raise RuntimeError("Contact kernel failed")
return cells[:n].copy(), sides[:n].astype(bool)
@@ -0,0 +1,167 @@
"""Feed measured non-traversable surface returns back into path search.
Costs represent rejected ground patches, not necessarily solid obstacles.
Keys may only refer to existing measured XYZ returns. The overlay never inserts
terrain, clears an obstacle, certifies support, or outlives its source geometry.
"""
from collections import OrderedDict
import math
import numpy as np
if __package__:
from .support_surface import SupportSurface
else:
from support_surface import SupportSurface
class SupportObstacles:
def __init__(self, blocked_cost):
self.blocked_cost = blocked_cost
self.keys = OrderedDict()
self.patches = {}
@staticmethod
def point_keys(points):
# ROS clouds are float32; assessments subtract/add a float64 pose.
# Normalize precision before rounding so the same measured return has
# one key on both sides of that numeric representation boundary.
return [tuple(row) for row in np.round(np.asarray(points, dtype=float).reshape(-1, 3), 6)]
def observe(self, points, terrain):
points = np.asarray(points, dtype=float).reshape(-1, 3)
if not np.isfinite(points).all() or len(points) > 512:
raise ValueError("Invalid support obstacle evidence")
if not len(points):
return
available = set(self.point_keys(np.asarray(terrain)[:, :3]))
keys = set(self.point_keys(points))
if not keys <= available:
raise ValueError("Support obstacle has no matching range return")
for key in dict.fromkeys(self.point_keys(points)):
self.keys.pop(key, None)
self.keys[key] = None
# This bounded search hint may forget old entries; the independent
# complete obstacle/support command gates still veto them. A long
# street must not fail just because it has more observed rough patches.
while len(self.keys) > 512:
evicted, _ = self.keys.popitem(last=False)
self.patches.pop(evicted, None)
def observe_patches(self, samples, terrain):
if len(samples) > 64:
raise ValueError("Too many support patches")
points = [sample["point_xyz"] for sample in samples]
queries = np.asarray([sample["query_xy"] for sample in samples], dtype=float).reshape(-1,2)
xyz = np.asarray(points, dtype=float).reshape(-1,3)
if (not np.isfinite(queries).all()
or np.any(np.linalg.norm(queries-xyz[:,:2],axis=1) > SupportSurface.radius_m+1e-6)):
raise ValueError("Support patch is not bound to its measured neighborhood")
self.observe(points, terrain)
for key, query in zip(self.point_keys(points), queries, strict=True):
if key in self.keys:
values = self.patches.setdefault(key, [])
xy = query.tolist()
if xy not in values:
# Keep bounded recent queries for the same measured return.
values.append(xy)
del values[:-4]
def revalidate(self, terrain, pose, contact_height_m, *, monitor):
"""Clear a pose-dependent hint only with positively observed support.
Retain the exact queried patch, not the nearest-return position. Loss
of neighbors remains unknown. Geometry expiration still belongs to
apply(), and the full live motion gate always independently rechecks.
"""
if not self.patches:
return
pose = np.asarray(pose, dtype=float)
surface = SupportSurface(terrain, pose, contact_height_m,
monitor.max_step, monitor.max_slope,
anchor_radius_m=math.hypot(monitor.half_length, monitor.half_width))
keys = list(self.patches)
lengths = [len(self.patches[k]) for k in keys]
queries = np.array([xy for k in keys for xy in self.patches[k]])
states, _ = monitor.classify_contacts(surface, queries - pose[:2])
offset = 0
for key, length in zip(keys, lengths, strict=True):
if np.all(states[offset:offset+length] == "observed-supported"):
self.keys.pop(key, None)
del self.patches[key]
offset += length
def observe_ahead(self, terrain, pose, contact_height_m, *, monitor, speed_mps):
"""Expose measured bad ground to search before a command reaches it.
The reactive sweep remains authoritative. This bounded contact-width
assessment only supplies search costs tied to existing returns;
unknown space produces no synthetic obstacle or ground. It uses the
robot's stopping distance, not scene coordinates or a route oracle.
"""
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
pose = np.asarray(pose, dtype=float)
if not len(terrain):
return 0
x, y, z, w = pose[3:]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
local = (terrain[:, :2]-pose[:2]) @ axes
bounds = monitor.command_bounds(speed_mps, 0)
reach = max(2*monitor.half_length, bounds['upper_xy_m'][0])
width = 3*monitor.half_width
candidates = np.flatnonzero((terrain[:,3] <= monitor.max_step+1e-4)
& (local[:,0] >= -monitor.half_length) & (local[:,0] <= reach)
& (np.abs(local[:,1]) <= width))
if not len(candidates):
return 0
# One real query per 15 cm cell. A farther query budget omission can
# only remove a search hint; it cannot waive the full command check.
_, indices = np.unique(np.floor(local[candidates]/SupportSurface.radius_m),
axis=0, return_index=True)
selected = candidates[indices]
selected = selected[np.argsort(np.linalg.norm(local[selected],axis=1))][:512]
surface = SupportSurface(terrain, pose, contact_height_m,
monitor.max_step, monitor.max_slope,
anchor_radius_m=math.hypot(monitor.half_length, monitor.half_width))
offsets = terrain[selected,:2]-pose[:2]
states, _ = monitor.classify_contacts(surface, offsets)
unsafe = offsets[states == 'observed-unsafe']
for start in range(0,len(unsafe),64):
self.observe_patches(surface.hazard_samples(unsafe[start:start+64]), terrain)
return len(unsafe)
def apply(self, terrain, *, pose=None, monitor=None):
"""Search costs only; preserve the independently measured terrain.
A failed ground query is tied to a nearby return, not a solid object at
that return. Do not turn its hint inside the current body into a global
no-path overlap. Keep the hint in memory and retain every original cost;
the independent command support check still owns newly entered ground.
"""
if not self.keys:
return terrain, 0
keys = self.point_keys(terrain[:, :3])
available = set(keys)
for key in list(self.keys):
if key not in available:
del self.keys[key]
self.patches.pop(key, None)
mask = np.fromiter((key in self.keys for key in keys), dtype=bool, count=len(keys))
if pose is not None:
if monitor is None:
raise ValueError("Support search scope requires robot geometry")
pose = np.asarray(pose, dtype=float)
if pose.shape != (7,) or not np.isfinite(pose).all():
raise ValueError("Invalid support search pose")
x, y, z, w = pose[3:]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
local = (terrain[:, :2] - pose[:2]) @ np.array(
[[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
occupied = ((np.abs(local[:, 0]) <= monitor.half_length)
& (np.abs(local[:, 1]) <= monitor.half_width))
mask &= ~occupied
result = terrain.copy()
result[mask, 3] = np.maximum(result[mask, 3], self.blocked_cost)
return result, int(mask.sum())
@@ -0,0 +1,313 @@
"""Observed-hazard veto and bounded motion under partial ground observations.
This policy does not certify hidden ground or load-bearing capacity. Unknown
sweep cells remain unknown. Fresh patches beyond both track ends allow only a
reduced command; they do not fill gaps in the causal terrain map. Body/obstacle,
semantic, attitude and observation-age guards remain independent vetoes.
"""
import math
import numpy as np
if __package__:
from .support_surface import SupportSurface
else:
from support_surface import SupportSurface
class SupportPolicy:
schema = "missioncore.support-policy/v1"
partial_speed_mps = 0.1
partial_yaw_rps = 0.15
lookahead_m = (0.2, 0.35, 0.5)
def __init__(self, monitor, *, observed_pivots=False, observed_approaches=False,
body_top_m=math.inf):
self.monitor = monitor
self.observed_pivots = observed_pivots
self.observed_approaches = observed_approaches
self.body_top_m = body_top_m
def live_terrain(self, points, pose, contact_height_m):
"""Split first-hit returns into ground candidates and raised obstacles.
A wall outside the swept body must not tilt a neighbouring ground fit.
Raised returns keep their independent full-body collision veto; they
never become zero-cost ground. Negative returns remain in the support
fit, so a visible drop cannot be removed by this partition.
"""
points = np.asarray(points, dtype=float).reshape(-1, 3)
pose = np.asarray(pose, dtype=float)
x, y, z, w = pose[3:]
up = np.array([2*(x*z + w*y), 2*(y*z - w*x), 1-2*(x*x+y*y)])
height = (points - pose[:3]) @ up + contact_height_m
raised = height > self.monitor.max_step + 1e-4
ground = np.column_stack((points, raised.astype(float) * (self.monitor.max_step + 1)))
body = raised & (height <= self.body_top_m)
obstacles = np.column_stack((points[body], np.full(int(body.sum()), self.monitor.max_step + 1)))
return ground, obstacles
def context(self, speed, yaw_rate, points, pose, contact_height_m, *, continuity_terrain=None):
"""Fresh observed patches beyond each track's entering end, no map fill."""
points = np.asarray(points, dtype=float).reshape(-1, 3)
pose = np.asarray(pose, dtype=float)
m = self.monitor
ground, _ = self.live_terrain(points, pose, contact_height_m)
surface = SupportSurface(
ground,
pose,
contact_height_m,
m.max_step,
m.max_slope,
anchor_radius_m=math.hypot(m.half_length, m.half_width),
continuity_terrain=continuity_terrain,
)
qx, qy, qz, qw = pose[3:]
yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
# Legacy geometry has no explicit contacts: require its full fresh
# sweep instead of inventing contact bands or upgrading pinned inputs.
if m.contacts is None:
fresh = m.assess_command_support(
speed, yaw_rate, [], pose, contact_height_m, surface=surface
)
return dict(available=fresh["admitted"], reason="legacy-fresh-sweep", patches=[])
patches = []
for name, (low, high) in zip(("left", "right"), m.contacts.bands, strict=True):
y = float((low[1] + high[1]) / 2)
side_speed = speed - yaw_rate * y
directions = (1, -1) if abs(side_speed) < 1e-6 else (1 if side_speed > 0 else -1,)
for direction in directions:
local = np.array([[direction * (m.half_length + d), y] for d in self.lookahead_m])
states, reasons = surface.classify(local @ axes.T)
patches.append(
dict(
side=name,
direction="front" if direction > 0 else "rear",
observed_supported=int(np.count_nonzero(states == "observed-supported")),
observed_unsafe=int(np.count_nonzero(states == "observed-unsafe")),
unknown=int(np.count_nonzero(states == "unknown")),
samples=len(states),
reasons=reasons,
)
)
return dict(
# Each positive sample already requires a non-collinear observed
# surface patch enclosing it. Count patches, not individual rays.
available=all(
p["observed_supported"] >= 1 and not p["observed_unsafe"] for p in patches
),
reason="fresh-track-end-patches",
lookahead_beyond_body_m=list(self.lookahead_m),
patches=patches,
)
def regulate(self, speed, yaw_rate, terrain, pose, contact_height_m, *, current_points):
m = self.monitor
requested = [speed, yaw_rate]
pivot_scale = 1.0
requested_support = None
surface = SupportSurface(terrain, pose, contact_height_m, m.max_step, m.max_slope,
anchor_radius_m=math.hypot(m.half_length, m.half_width))
current = np.asarray(current_points, dtype=float).reshape(-1, 3)
fresh_ground, fresh_obstacles = self.live_terrain(current, pose, contact_height_m)
fresh_surface = SupportSurface(fresh_ground,
pose, contact_height_m, m.max_step, m.max_slope,
anchor_radius_m=math.hypot(m.half_length, m.half_width), continuity_terrain=terrain)
support = m.assess_command_support(speed, yaw_rate, terrain, pose, contact_height_m,
surface=surface)
def live_sweep(v, w):
result = m.assess_command_support(v, w, terrain, pose, contact_height_m,
surface=fresh_surface)
result["body_clear"] = m.command_footprint_clear(v, w, fresh_obstacles, pose)
return result
def fresh_clear(result):
return not result["unsafe_samples"] and result["body_clear"]
fresh_sweep = live_sweep(speed, yaw_rate)
requested_fresh = fresh_sweep
if (abs(speed) > 0.02
and (not support["admitted"] or not fresh_clear(fresh_sweep))):
# A remote end of the high-speed stopping horizon is not a reason
# to reject every forward command. Find a wholly observed stopping
# envelope along the SAME arc. Hazards remain in the map, and no
# partially observed candidate gains ordinary driving authority.
# Use the same physical command floor as collision admission.
# A 0.1 m/s sampling floor otherwise discards shorter, completely
# observed stops beside a local rough patch before any search.
lower = min(m.minimum_command_scale(speed, yaw_rate),
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12))
narrow = m.assess_command_support(speed * lower, yaw_rate * lower,
terrain, pose, contact_height_m, surface=surface)
narrow_fresh = live_sweep(speed * lower, yaw_rate * lower)
if (narrow["admitted"] and fresh_clear(narrow_fresh)
and m.command_footprint_clear(
speed * lower, yaw_rate * lower, terrain, pose)):
upper = 1.0
original = requested_support = support
for _ in range(7):
middle = (lower + upper) / 2
candidate = m.assess_command_support(speed * middle, yaw_rate * middle,
terrain, pose, contact_height_m, surface=surface)
candidate_fresh = live_sweep(speed * middle, yaw_rate * middle)
if (candidate["admitted"] and fresh_clear(candidate_fresh)
and m.command_footprint_clear(
speed * middle, yaw_rate * middle, terrain, pose)):
lower, narrow, narrow_fresh = middle, candidate, candidate_fresh
else:
upper = middle
narrow["requested_support"] = {key: original[key] for key in (
"status", "unknown_samples", "unsafe_samples", "bounds")}
narrow["roughness_obstacles_xyz"] = original["roughness_obstacles_xyz"]
narrow["support_obstacle_samples"] = original["support_obstacle_samples"]
pivot_scale = lower
speed, yaw_rate, support = speed * lower, yaw_rate * lower, narrow
fresh_sweep = narrow_fresh
else:
lower = min(1.0, self.partial_speed_mps / abs(speed),
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12))
narrow = m.assess_command_support(speed * lower, yaw_rate * lower,
terrain, pose, contact_height_m, surface=surface)
narrow_fresh = live_sweep(speed * lower, yaw_rate * lower)
if ((support["unsafe_samples"] or not fresh_clear(fresh_sweep))
and not narrow["unsafe_samples"] and fresh_clear(narrow_fresh)
and m.command_footprint_clear(speed * lower, yaw_rate * lower, terrain, pose)):
# Apply the existing partial-observation policy to the actual
# shorter stopping sweep, not to the discarded fast proposal.
# This grants at most crawl speed and still requires both fresh
# track-end patches below. Unknown remains unknown; a measured
# hazard in this sweep or its live context still vetoes motion.
narrow["requested_support"] = {key: support[key] for key in (
"status", "unknown_samples", "unsafe_samples", "bounds")}
narrow["roughness_obstacles_xyz"] = support["roughness_obstacles_xyz"]
narrow["support_obstacle_samples"] = support["support_obstacle_samples"]
requested_support = support
pivot_scale = lower
speed, yaw_rate, support = speed * lower, yaw_rate * lower, narrow
fresh_sweep = narrow_fresh
if (
self.observed_pivots
and abs(speed) < 1e-8
and 0.1 < abs(yaw_rate) <= self.partial_yaw_rps + 1e-8
and (not support["admitted"] or not fresh_clear(fresh_sweep))
):
# As for forward speed, a slower pivot has its own shorter stop
# envelope. Admit it only when that complete envelope is measured
# and clear; the original hazard remains in the map for the next
# control tick and cannot be crossed by repeated blind commands.
slower = math.copysign(0.1, yaw_rate)
narrow = m.assess_command_support(0, slower, terrain, pose, contact_height_m)
narrow_fresh = live_sweep(0, slower)
if (narrow["admitted"] and fresh_clear(narrow_fresh)
and m.command_footprint_clear(0, slower, terrain, pose)):
narrow["requested_pivot_support"] = {
key: support[key]
for key in ("status", "unknown_samples", "unsafe_samples", "bounds")
}
pivot_scale = abs(slower / yaw_rate)
yaw_rate, support = slower, narrow
fresh_sweep = live_sweep(speed, yaw_rate)
moving = abs(speed) + abs(yaw_rate) > 1e-8
scale, reason, context = 1.0, ("observed-support-speed-limit" if pivot_scale < 1 else "observed-support"), None
if not moving:
reason = "hold"
elif support["unsafe_samples"] or not fresh_clear(fresh_sweep):
# No completely observed shorter stopping envelope was available.
# A nearby measured hazard must stop both tracks.
scale, reason = 0.0, "observed-unsafe-support"
elif (
self.observed_pivots
and abs(speed) < 1e-8
and abs(yaw_rate) <= self.partial_yaw_rps + 1e-8
and support["status"] == "observed-supported"
):
# Only a completely measured sweep may use retained static ground.
# Distant track-end patches outside that sweep are not pivot ground.
# Fresh ranges, new measured hazards, and the separate obstacle/
# pose/time/stop gates remain mandatory. Unknown sweep is never
# admitted by this branch, nor is translational reverse enabled.
current = np.asarray(current_points, dtype=float).reshape(-1, 3)
fresh = m.assess_command_support(
speed,
yaw_rate,
np.column_stack((current, np.zeros(len(current)))),
pose,
contact_height_m,
surface=fresh_surface,
)
if len(current) < 50:
scale, reason = 0.0, "insufficient-fresh-ground"
elif fresh["unsafe_samples"]:
scale, reason = 0.0, "observed-unsafe-support"
else:
reason = "observed-static-ground-pivot"
context = {
"available": True,
"reason": "entire-sweep-observed; live-range-veto",
"patches": [],
}
else:
context = self.context(speed, yaw_rate, current_points, pose, contact_height_m,
continuity_terrain=terrain)
if any(p["observed_unsafe"] for p in context["patches"]):
scale, reason = 0.0, "observed-unsafe-support"
elif not context["available"]:
scale, reason = 0.0, "insufficient-fresh-ground"
elif support["status"] != "observed-supported":
scale = min(
1.0,
self.partial_speed_mps / max(abs(speed), 1e-12),
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12),
)
reason = "partial-observation-limit"
if (scale == 0 and self.observed_approaches and speed > 0
and support["status"] == "observed-supported"):
# The fixed distant track-end probes are context, not the
# commanded sweep. A curb beyond that sweep must not prevent
# stopping on the fully observed ground before it. This branch
# never fills unknown ground, admits reverse, or shrinks away
# a hazard inside the ORIGINAL command's full stopping bounds.
# It uses causal range memory through the normal map owner;
# current raw returns independently veto changed ground.
current = np.asarray(current_points, dtype=float).reshape(-1, 3)
fresh = m.assess_command_support(
speed, yaw_rate,
np.column_stack((current, np.zeros(len(current)))),
pose, contact_height_m,
surface=fresh_surface,
)
context["current_sweep"] = {key: fresh[key] for key in (
"status", "supported_samples", "unknown_samples", "unsafe_samples")}
if len(current) < 50:
reason = "insufficient-fresh-ground"
elif fresh["unsafe_samples"]:
reason = "observed-unsafe-support"
else:
scale = min(1.0, self.partial_speed_mps / speed,
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12))
reason = "observed-static-ground-approach"
if scale == 0 and requested_support is not None:
support = requested_support
fresh_sweep = requested_fresh
support["fresh_sweep"] = {key: fresh_sweep[key] for key in (
"status", "supported_samples", "unknown_samples", "unsafe_samples", "support_reasons", "body_clear")}
decision = dict(
schema_version=self.schema,
reason=reason,
allowed=scale > 0,
scale=scale * pivot_scale,
requested_command=requested,
output_command=[speed * scale, yaw_rate * scale],
partial_limits=dict(
speed_mps=self.partial_speed_mps, yaw_rate_rps=self.partial_yaw_rps
),
fresh_context=context,
scope=(
"observed-hazard veto and partial-observation limits; "
"hidden ground is not certified"
),
)
support.update(enforced=True, policy=decision)
return speed * scale, yaw_rate * scale, scale * pivot_scale, support
@@ -0,0 +1,304 @@
"""Sampled observed ground support, distinct from absence of obstacle returns.
Unknown patches never become ground through nearest-neighbour extrapolation.
This indexes the current causal terrain observation, not scene or collider data.
"""
import math
from collections import Counter, deque
import numpy as np
if __package__:
from . import support_native
else:
import support_native
class SupportSurface:
radius_m = 0.15
@staticmethod
def ground_layer(terrain, max_step_m):
"""Keep measured lower-layer returns for the elevation fit.
A traversable-height cost is not a ground classification: the foot of
a wall can have the same coarse cost as the pavement next to it. Use
the lowest measured height in a range-sized XY column that ALSO
contains a confirmed raised obstacle, retaining its existing 5 cm
roughness band. Ordinary relief/steps without that separate obstacle
evidence stay intact. Never add or interpolate a floor.
The complete, unchanged cloud still owns collision/semantic checks.
Fresh and retained layers are filtered separately, so memory cannot
supply missing fresh measurements. Local slopes and drops are checked
after this ground/non-ground separation.
"""
ground = terrain[:, 3] <= max_step_m + 1e-4
points = terrain[:, :3]
if not ground.any():
return points[ground]
# Match the observed range voxel resolution; no scene-dependent scale.
_, inverse = np.unique(np.floor(points[:, :2] / .06).astype(int),
axis=0, return_inverse=True)
lowest = np.full(int(inverse.max()) + 1, np.inf)
np.minimum.at(lowest, inverse[ground], points[ground, 2])
obstacle_top = np.full(len(lowest), -np.inf)
np.maximum.at(obstacle_top, inverse[~ground], points[~ground, 2])
layered = obstacle_top > lowest + max_step_m + 1e-4
return points[ground & (~layered[inverse] | (points[:, 2] <= lowest[inverse] + .05))]
def __init__(self, terrain, pose, contact_height_m, max_step_m, max_slope, *, anchor_radius_m=0,
continuity_terrain=None):
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
self.pose = np.asarray(pose, dtype=float)
if (
not np.isfinite(terrain).all()
or self.pose.shape != (7,)
or not np.isfinite(self.pose).all()
or not math.isfinite(contact_height_m)
or contact_height_m <= 0
):
raise ValueError("Invalid support observation")
x, y, z, w = self.pose[3:]
self.up = np.array([2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)])
self.contact_height = contact_height_m
self.max_step = max_step_m
self.max_slope = max_slope
if not math.isfinite(anchor_radius_m) or anchor_radius_m < 0:
raise ValueError("Invalid support anchor radius")
self.anchor_radius = anchor_radius_m + self.radius_m if anchor_radius_m else 0
self.ground = self.ground_layer(terrain, max_step_m) - self.pose[:3]
continuity = np.asarray(continuity_terrain if continuity_terrain is not None else [],
dtype=float).reshape(-1, 4)
if not np.isfinite(continuity).all():
raise ValueError("Invalid continuity observation")
self.continuity = self.ground_layer(continuity, max_step_m) - self.pose[:3]
self.native = support_native.NativeSurface(self) if support_native.LIBRARY else None
self.buckets = {}
for index, key in enumerate(np.floor(self.ground[:, :2] / self.radius_m).astype(int) if self.native is None else []):
self.buckets.setdefault(tuple(key), []).append(index)
self.results = {}
self.neighborhoods = {}
self.raised_obstacles = {}
self.connected = self._connected_ground() if self.native is None else None
self.contact_results = {}
def classify_contacts(self, offsets, contact_width_m):
"""Check the spatial extent of local slope/roughness under a track.
Footprint filtering follows ETH traversability_estimation's
checkForSlope/checkForRoughness: a cell's raw surface quality and the
extent of that quality are separate. Here the narrower actual contact
width supplies the scale (not a gap-bridging permission). Every sample
in the surrounding 3-cell disk must have measured ground, and any
height discontinuity retains the raw veto. Unknown ground is unchanged.
"""
offsets = np.asarray(offsets, dtype=float).reshape(-1, 2)
states, reasons = self.classify(offsets)
states, reasons = states.astype(object), Counter(reasons)
spacing, radius = .05, .15
delta = np.array([[x*spacing, y*spacing] for x in range(-3,4)
for y in range(-3,4) if x*x+y*y<=9])
critical = math.floor(2*radius*(contact_width_m/3)/spacing**2)
for i in np.flatnonzero(states == 'observed-unsafe'):
point = offsets[i]
_, raw = self.classify([point])
reason = next(iter(raw))
if reason not in {'slope', 'roughness'}:
continue
key = (tuple(np.round(point,12)), float(contact_width_m))
if key not in self.contact_results:
_, surrounding = self.classify(point+delta)
forbidden = set(surrounding)-{'observed-patch','slope','roughness'}
count = surrounding.get('slope',0)+surrounding.get('roughness',0)
self.contact_results[key] = not forbidden and count<=critical
if self.contact_results[key]:
states[i] = 'observed-supported'
reasons[reason] -= 1
reasons['observed-local-relief'] += 1
return states, {key:value for key,value in reasons.items() if value}
def _connected_ground(self):
"""Measured continuity from contact-adjacent ground, never across gaps.
Attitude predicts contact-adjacent height only. It cannot extrapolate
the ground beyond the vehicle. A distant patch may depart from that
plane only through returns separated by <=12 cm and <=max step.
Every query still needs enclosing returns, slope/roughness checks, and
an independent local jump veto, even if a graph route goes around it.
"""
# Retained causal returns can anchor height behind the current sensor's
# blind zone. They NEVER enter the fresh patch fit or fill its missing
# returns. A changed fresh patch still owns slope, jumps and roughness.
ground = np.concatenate((self.ground, self.continuity))
buckets = {}
for i, key in enumerate(np.floor(ground[:, :2] / self.radius_m).astype(int)):
buckets.setdefault(tuple(key), []).append(i)
reached = np.zeros(len(ground), dtype=bool)
if self.anchor_radius <= 0 or self.up[2] <= 0:
return reached[:len(self.ground)]
expected = (-self.contact_height - ground[:, :2] @ self.up[:2]) / self.up[2]
reached[:] = ((np.linalg.norm(ground[:, :2], axis=1) <= self.anchor_radius)
& (np.abs(ground[:, 2] - expected) <= self.max_step + 1e-4))
pending = deque(np.flatnonzero(reached).tolist())
while pending:
index = pending.popleft(); point = ground[index]
x, y = np.floor(point[:2] / self.radius_m).astype(int)
neighbors = [i for dx in (-1, 0, 1) for dy in (-1, 0, 1)
for i in buckets.get((x + dx, y + dy), ()) if not reached[i]]
if not neighbors:
continue
indices = np.asarray(neighbors, dtype=int)
delta = ground[indices] - point
links = indices[(np.sum(delta[:, :2] ** 2, axis=1) <= .12 ** 2)
& (np.abs(delta[:, 2]) <= self.max_step + 1e-4)]
reached[links] = True
pending.extend(links.tolist())
return reached[:len(self.ground)]
def classify(self, offsets):
"""Return observed-supported, observed-unsafe or unknown per XY sample."""
offsets = np.asarray(offsets, dtype=float).reshape(-1, 2)
if not np.isfinite(offsets).all():
raise ValueError("Invalid support samples")
if self.native is not None:
states, reasons, raised = self.native.classify(offsets)
for point in raised + self.pose[:3]:
self.raised_obstacles[tuple(np.round(point, 6))] = point.tolist()
return states, dict(Counter(reasons))
keys = [tuple(point) for point in np.round(offsets, 12)]
pending = {}
for point, sample_key in zip(offsets, keys):
if sample_key not in self.results:
key = tuple(np.floor(point / self.radius_m).astype(int))
pending.setdefault(key, {})[sample_key] = point
samples = []
for key, group in pending.items():
if key not in self.neighborhoods:
x, y = key
indices = sorted(i for dx in (-1, 0, 1) for dy in (-1, 0, 1)
for i in self.buckets.get((x + dx, y + dy), ()))
self.neighborhoods[key] = np.asarray(indices, dtype=int)
indices = self.neighborhoods[key]
samples.extend((sample_key, point, self.ground[indices], self.connected[indices])
for sample_key, point in group.items())
# Batch across buckets too: hundreds of tiny LAPACK calls on one HTTP
# control transaction used to outlive the command watchdog. Each sample
# still owns exactly the same returns and geometric tests.
for begin in range(0, len(samples), 128):
batch = samples[begin:begin + 128]
size = max(3, max(len(item[2]) for item in batch))
nearby = np.zeros((len(batch), size, 3))
present = np.zeros((len(batch), size), bool)
connected = np.zeros((len(batch), size), bool)
for i, (_, _, neighbors, continuity) in enumerate(batch):
nearby[i, :len(neighbors)] = neighbors
present[i, :len(neighbors)] = True
connected[i, :len(neighbors)] = continuity
states, reasons = self._classify_batch(np.array([item[1] for item in batch]), nearby, present, connected)
self.results.update((item[0], (state, reason))
for item, state, reason in zip(batch, states, reasons))
values = [self.results[key] for key in keys]
return (np.array([v[0] for v in values], dtype=str),
dict(Counter(v[1] for v in values)))
def hazard_samples(self, unsafe_offsets):
"""Bind rejected surface samples to real returns for path-search costs.
These represent non-traversable patches, not necessarily solid objects.
Unknown queries must not call this method: missing ground supplies no
return to invent. Limit feedback work; the complete command support
assessment remains the authority even when this proposal layer is sparse.
"""
offsets = np.asarray(unsafe_offsets, dtype=float).reshape(-1, 2)
if not len(offsets) or not len(self.ground):
return []
if len(offsets) > 64:
offsets = offsets[np.linspace(0, len(offsets)-1, 64).astype(int)]
selected = []
for point in offsets:
delta = self.ground[:, :2] - point
distance = np.einsum("ij,ij->i", delta, delta)
index = int(np.argmin(distance))
if distance[index] <= self.radius_m ** 2 + 1e-12:
selected.append(dict(
point_xyz=(self.ground[index] + self.pose[:3]).tolist(),
query_xy=(point + self.pose[:2]).tolist()))
return selected
def _classify_batch(self, points, nearby, present, connected):
states = np.full(len(points), "unknown", dtype=object)
reasons = np.full(len(points), "insufficient-returns", dtype=object)
xy = nearby[:, :, :2] - points[:, None, :]
distance2 = np.sum(xy * xy, axis=2)
mask = present & (distance2 <= self.radius_m ** 2)
counts = mask.sum(axis=1)
valid = counts >= 3
if not valid.any():
return states, reasons
# Analytic 2x2 covariance eigenvalue equals eigvalsh(cov(xy)).
weights = mask.astype(float)
total = np.maximum(counts, 1)
mean = np.sum(xy * weights[:, :, None], axis=1) / total[:, None]
centred = xy - mean[:, None, :]
covariance = np.einsum("bni,bnj,bn->bij", centred, centred, weights)
covariance /= np.maximum(counts - 1, 1)[:, None, None]
a, b, d = covariance[:, 0, 0], covariance[:, 0, 1], covariance[:, 1, 1]
eigen_min = (a + d - np.hypot(a - d, 2 * b)) / 2
reasons[valid] = "collinear-returns"
valid &= eigen_min >= 1e-5
if not valid.any():
return states, reasons
angles = np.sort(np.where(mask, np.arctan2(xy[:, :, 1], xy[:, :, 0]), np.inf), axis=1)
# Padding never participates in a gap. The wrap gap closes the exact
# angular hull, including a sample coincident with an observed return.
gaps = np.zeros((len(points), nearby.shape[1] - 1))
np.subtract(angles[:, 1:], angles[:, :-1], out=gaps,
where=np.arange(nearby.shape[1] - 1)[None, :] < (counts - 1)[:, None])
last = angles[np.arange(len(points)), np.maximum(counts - 1, 0)]
wrap = np.zeros(len(points))
np.subtract(angles[:, 0] + 2 * math.pi, last, out=wrap, where=counts > 0)
outside = ((np.where(mask, distance2, np.inf).min(axis=1) > 1e-12)
& (np.maximum(gaps.max(axis=1), wrap) > math.pi + 1e-6))
reasons[valid] = "outside-observed-patch"
valid &= ~outside
if self.up[2] <= 0:
states[valid], reasons[valid] = "observed-unsafe", "body-attitude"
return states, reasons
indices = np.flatnonzero(valid)
if not len(indices):
return states, reasons
# Centre the least-squares system before solving; covariance has already
# rejected rank-deficient patches. Solve all accepted patches at once.
w = weights[indices]
z = nearby[indices, :, 2]
z_mean = np.sum(w * z, axis=1) / counts[indices]
rhs = np.einsum("bni,bn,bn->bi", centred[indices], w, z)
gram = covariance[indices] * (counts[indices] - 1)[:, None, None]
slope = np.linalg.solve(gram, rhs[..., None])[..., 0]
intercept = z_mean - np.sum(slope * mean[indices], axis=1)
expected = (-self.contact_height - points[indices] @ self.up[:2]) / self.up[2]
residual = z - (np.einsum("bni,bi->bn", xy[indices], slope) + intercept[:, None])
rough = np.where(mask[indices], np.abs(residual), 0).max(axis=1) > 0.05
bad_height = np.abs(intercept - expected) > self.max_step + 1e-4
# Relax the body-plane comparison only with actual connected returns.
# Do not fill holes, extrapolate a surface or erase a local ledge.
bad_height &= ~np.all(~mask[indices] | connected[indices], axis=1)
for j, index in enumerate(indices):
patch = nearby[index][mask[index]]
delta = patch[:, None, :] - patch[None, :, :]
bad_height[j] |= np.any((np.sum(delta[:, :, :2] ** 2, axis=2) <= .12 ** 2)
& (np.abs(delta[:, :, 2]) > self.max_step + 1e-4))
bad_slope = np.linalg.norm(slope, axis=1) > self.max_slope + 1e-4
states[indices] = np.where(bad_slope | bad_height | rough, "observed-unsafe", "observed-supported")
reasons[indices] = np.where(bad_slope, "slope", np.where(bad_height, "height-discontinuity",
np.where(rough, "roughness", "observed-patch")))
if len(self.continuity):
detached = (~np.all(~mask[indices] | connected[indices], axis=1)
& ~bad_slope & ~bad_height & ~rough)
states[indices[detached]], reasons[indices[detached]] = "unknown", "unanchored-ground"
raised = ((residual > 0.05) & mask[indices]
& (rough & ~bad_height & ~bad_slope)[:, None])
for point in nearby[indices][raised] + self.pose[:3]:
self.raised_obstacles[tuple(np.round(point, 6))] = point.tolist()
return states, reasons
@@ -1,6 +1,9 @@
// Exact close-pair hazard and connectedness test; same predicates as NumPy.
// C ABI keeps this numerical hot loop independent of ROS and Python versions.
#include <cmath>
#include <algorithm>
#include <cstdint>
#include <map>
#include <vector>
template<class T> int connected_grade(const T* p, int n) {
if (n <= 0) return 0;
@@ -21,3 +24,56 @@ template<class T> int connected_grade(const T* p, int n) {
}
extern "C" int terrain_connected_f32(const float* p,int n) {return connected_grade(p,n);}
extern "C" int terrain_connected_f64(const double* p,int n) {return connected_grade(p,n);}
// Exact counterpart of terrain_costs._neighborhoods. Return source indices in
// source order; Python retains the unchanged fitting and hazard predicates.
template<class T> struct Neighborhoods {
std::vector<T> points;
std::map<std::pair<int64_t,int64_t>,std::vector<int>> cells;
Neighborhoods(const T* p,int n): points(p,p+3*n) {
for(int i=0;i<n;i++) cells[key(i)].push_back(i);
}
std::pair<int64_t,int64_t> key(int i) const {
return {int64_t(std::floor(points[3*i]/T(0.4))),
int64_t(std::floor(points[3*i+1]/T(0.4)))};
}
int query(int i,int* output) const {
const auto k=key(i);
int count=0;
for(int dx=-1;dx<=1;dx++) for(int dy=-1;dy<=1;dy++) {
const auto found=cells.find({k.first+dx,k.second+dy});
if(found==cells.end()) continue;
for(int j:found->second) {
const T x=points[3*j]-points[3*i], y=points[3*j+1]-points[3*i+1];
if(std::sqrt(x*x+y*y)<=T(0.4)) output[count++]=j;
}
}
std::sort(output,output+count);
return count;
}
// Batch the existing Python count/span rejection before allocating a
// NumPy neighborhood per point. Relative subtraction and span retain T's
// rounding, exactly as terrain[index-neighbors] - terrain[index] does.
int screen(const int* indices,int n,int minimum,double maximum_span,int* output) const {
std::vector<int> nearby(points.size()/3);
int kept=0;
for(int k=0;k<n;k++) {
const int i=indices[k], count=query(i,nearby.data());
if(count<minimum) continue;
T low=points[3*nearby[0]+2]-points[3*i+2], high=low;
for(int j=1;j<count;j++) {
const T z=points[3*nearby[j]+2]-points[3*i+2];
low=std::min(low,z); high=std::max(high,z);
}
if(double(T(high-low))<=maximum_span) output[kept++]=i;
}
return kept;
}
};
#define NEIGHBOR_API(T,S) \
extern "C" void* terrain_neighbors_create_##S(const T* p,int n) {return new Neighborhoods<T>(p,n);} \
extern "C" int terrain_neighbors_query_##S(void* h,int i,int* out) {return static_cast<Neighborhoods<T>*>(h)->query(i,out);} \
extern "C" int terrain_neighbors_screen_##S(void* h,const int* i,int n,int minimum,double span,int* out) {return static_cast<Neighborhoods<T>*>(h)->screen(i,n,minimum,span,out);} \
extern "C" void terrain_neighbors_destroy_##S(void* h) {delete static_cast<Neighborhoods<T>*>(h);}
NEIGHBOR_API(float,f32)
NEIGHBOR_API(double,f64)
@@ -10,6 +10,7 @@ surfaces, excessive roughness and sparse/unknown support retain the CMU cost.
import ctypes
import hashlib
import math
import weakref
from collections import OrderedDict
from pathlib import Path
@@ -51,15 +52,20 @@ def connected_grade(nearby):
reached = expanded
def underbody_support_costs(terrain, pose, contact_height_m=0.37):
def underbody_support_costs(terrain, pose, contact_height_m=None, *, geometry):
"""Reconcile low returns already inside the current chassis footprint.
CMU's neighbourhood ground reference can label the supported terrain under
the chassis as a body collision. Use measured pose and the declared contact
height only inside the body (with a 5 cm inset), never for terrain ahead.
height only inside the actual body, never for terrain ahead. A clearance
reserve belongs outside the body; insetting the occupied area leaves low
ground beneath track edges misclassified as an impossible body collision.
Retain drops, high returns and excessive tilt. The 8 cm band has 2 cm reserve
below the physically qualified 10 cm step; raw terrain memory is unchanged.
"""
if contact_height_m is None:
contact_height_m = geometry["body_contact_height_m"]
extent = np.array([geometry["length_m"], geometry["width_m"]]) / 2
result = terrain.copy()
x, y, z, w = pose[3:]
up = np.array([2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)])
@@ -70,13 +76,13 @@ def underbody_support_costs(terrain, pose, contact_height_m=0.37):
local = (terrain[:, :2] - pose[:2]) @ axes
height = (terrain[:, :3] - pose[:3]) @ up + contact_height_m
supported = (
(np.abs(local) < 0.45).all(axis=1) & (np.abs(height) <= 0.08) & (terrain[:, 3] > 0.1)
(np.abs(local) < extent).all(axis=1) & (np.abs(height) <= 0.08) & (terrain[:, 3] > 0.1)
)
result[supported, 3] = np.abs(height[supported])
return result, int(supported.sum())
def _neighborhoods(terrain, radius=0.4):
def _reference_neighborhoods(terrain, radius=0.4):
"""Exact radius neighborhoods without scanning the whole accumulated map.
Returns in the nine adjacent cells include every possible neighbor. Keep
@@ -107,13 +113,68 @@ def _neighborhoods(terrain, radius=0.4):
return around
class _NativeNeighborhoods:
def __init__(self, terrain):
self.terrain = terrain
suffix = "f32" if terrain.dtype.itemsize == 4 else "f64"
dtype = ctypes.c_float if suffix == "f32" else ctypes.c_double
create = getattr(_NATIVE, "terrain_neighbors_create_" + suffix)
create.argtypes = [ctypes.POINTER(dtype), ctypes.c_int]
create.restype = ctypes.c_void_p
self.query = getattr(_NATIVE, "terrain_neighbors_query_" + suffix)
self.query.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
self.query.restype = ctypes.c_int
destroy = getattr(_NATIVE, "terrain_neighbors_destroy_" + suffix)
destroy.argtypes = [ctypes.c_void_p]
destroy.restype = None
xyz = np.ascontiguousarray(terrain[:, :3])
self.handle = create(xyz.ctypes.data_as(ctypes.POINTER(dtype)), len(xyz))
self.finalizer = weakref.finalize(self, destroy, self.handle)
self.indices = np.empty(len(terrain), dtype=np.int32)
self.screen = getattr(_NATIVE, "terrain_neighbors_screen_" + suffix, None)
if self.screen is not None:
self.screen.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int),
ctypes.c_int, ctypes.c_int, ctypes.c_double,
ctypes.POINTER(ctypes.c_int)]
self.screen.restype = ctypes.c_int
def candidates(self, indices):
if self.screen is None:
return indices # Previous pinned kernel retains the reference path.
indices = np.ascontiguousarray(indices, dtype=np.int32)
output = np.empty_like(indices)
count = self.screen(self.handle, indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int)),
len(indices), 8, 0.8*math.tan(math.radians(25+1e-4))+0.15,
output.ctypes.data_as(ctypes.POINTER(ctypes.c_int)))
return output[:count]
def __call__(self, index):
count = self.query(
self.handle, int(index), self.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
)
return self.terrain[self.indices[:count], :3] - self.terrain[index, :3]
def _neighborhoods(terrain):
if (
_NATIVE is not None
and hasattr(_NATIVE, "terrain_neighbors_create_f32")
and terrain.dtype in (np.dtype("float32"), np.dtype("float64"))
):
return _NativeNeighborhoods(terrain)
return _reference_neighborhoods(terrain)
def supported_slope_costs(terrain, cache=None):
result = terrain.copy()
if len(terrain) < 8:
return result, 0
around = _neighborhoods(terrain)
corrected = 0
for index in np.flatnonzero(terrain[:, 3] > 0.1):
indices = np.flatnonzero(terrain[:, 3] > 0.1)
if isinstance(around, _NativeNeighborhoods):
indices = around.candidates(indices)
for index in indices:
nearby = around(index)
if len(nearby) < 8:
continue
@@ -0,0 +1,171 @@
"""Bounded observed placement before a turn; every motion still needs admission.
A range-blind start can be traversed with the existing partial-forward policy,
but cannot authorize a pivot. This searches an observed placement ahead before
attempting the declared turn. It never fills ground, credits route progress or
uses hidden geometry. The outer route guard still owns the allowed corridor.
"""
import math
import numpy as np
class TurnStaging:
search_batch_size = 12
def __init__(self, monitor):
self.monitor = monitor
self.key = self.active = None
self.attempts = 0
self.last_search = -math.inf
self.candidates = []
self.search_pose = None
self.search_cursor = 0
self.transition = None
def reset_target(self, target):
key = target["key"] if target else None
if key != self.key:
self.key, self.active, self.attempts = key, None, 0
self.last_search = -math.inf
self.search_pose, self.search_cursor = None, 0
self.transition = None
def current(self, pose, target, seconds):
self.reset_target(target)
if self.active is not None and seconds > self.active["deadline_seconds"]:
self.active = None
return self.active
def propose(self, terrain, permitted, pose, target, seconds, height):
self.reset_target(target)
if self.active or self.attempts >= 2:
return self.active
if self.search_pose is not None and (
np.linalg.norm(np.asarray(pose[:3]) - self.search_pose[:3]) > 0.025
or abs(float(np.dot(pose[3:], self.search_pose[3:]))) < math.cos(0.025)
):
self.search_pose, self.search_cursor = None, 0
if self.search_pose is None:
if seconds - self.last_search < 2:
return None
self.last_search = seconds
self.search_pose = np.asarray(pose).copy()
self.search_cursor = 0
self.candidates = []
if target is None or math.dist(pose[:2], target["xy"]) <= 0.1:
return None
x, y, z, w = pose[3:]
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
bearing = math.atan2(target["xy"][1] - pose[1], target["xy"][0] - pose[0])
error = math.atan2(math.sin(bearing - yaw), math.cos(bearing - yaw))
if abs(error) <= 0.3:
return None
rate = math.copysign(0.1, error)
m = self.monitor
up = np.array([2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)])
if up[2] <= 0:
return None
# The smallest fully observed placement wins. This is only a proposal;
# current-frame CMU, obstacle, support and corridor checks govern travel.
# A decimetre search can skip the entire admissible interval between
# the range blind strip and a measured obstacle. Search centimetre-scale
# placements and a small forward fan; no candidate changes the guards.
candidates = [
(distance, lateral)
for distance in np.arange(0.2, 1.201, 0.025)
for lateral in (0.0, 0.1, -0.1, 0.2, -0.2)
if abs(lateral) <= distance * 0.25
]
# Only candidate coordinates survive between observations. Every
# admission is recomputed on the current measured map. Bound the work
# per transaction so a failed search cannot starve the camera deadman.
batch = candidates[self.search_cursor : self.search_cursor + self.search_batch_size]
self.search_cursor += len(batch)
for distance, lateral in batch:
candidate = np.asarray(pose).copy()
shift = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) @ [
distance,
lateral,
]
candidate[:2] += shift
candidate[2] -= float(up[:2] @ shift) / up[2]
body = m.assess_pose(terrain, candidate, height)
diagnostic = {"distance_m": float(distance), "lateral_m": lateral, "body": body}
self.candidates.append(diagnostic)
if not body["admitted"]:
continue
sweep = m.assess_command_support(0, rate, terrain, candidate, height)
scale = m.regulate_command(0, rate, terrain, candidate)[2]
diagnostic.update(
pivot_supported=sweep["supported_samples"],
pivot_samples=sweep["support_samples"],
pivot_unsafe=sweep["unsafe_samples"],
obstacle_scale=scale,
)
if not sweep["admitted"] or scale != 1:
continue
self.attempts += 1
self.active = {
"schema_version": "missioncore.observed-turn-placement/v1",
"target_key": self.key,
"goal": [*candidate[:2].tolist(), candidate[2] - height],
"started_seconds": seconds,
"deadline_seconds": seconds + 60,
"attempt": self.attempts,
"phase": "observing",
"positive_surface_admitted": False,
"body": body,
"initial_pivot": sweep,
"authority": "observed-goal-proposal; no-motion-or-route-arrival-permission",
}
return self.active
if self.search_cursor >= len(candidates):
self.search_pose, self.search_cursor = None, 0
self.last_search = seconds
return None
def confirm_surface(self, terrain, permitted, pose, height):
"""Recheck the fixed placement against this observation before travel.
Geometry may request a camera view. Only positive surface evidence can
release translation, and a later rejection stops it again.
"""
if self.active is None:
return False
candidate = np.asarray(pose).copy()
candidate[:3] = self.active["goal"]
candidate[2] += height
body = self.monitor.assess_pose(terrain, candidate, height, support_terrain=permitted)
if not body["collision_free"]:
# A measured obstacle or explicit forbidden surface invalidates
# this destination. Waiting for a better view cannot make that
# proposal usable. A subsequent transaction may search again on
# the changed map, within the original two-attempt budget.
self.active = None
self.search_pose, self.search_cursor = None, 0
self.transition = "turn-placement-invalidated"
return False
admitted = bool(body["admitted"])
self.active.update(
phase="placing" if admitted else "observing",
positive_surface_admitted=admitted,
surface_body=body,
)
if admitted and math.dist(pose[:2], self.active["goal"][:2]) <= 0.12:
actual = self.monitor.assess_pose(terrain, pose, height, support_terrain=permitted)
# The controller's stopping disk is not proof of the measured
# pose. Both turn directions need a full observed sweep before
# releasing the placement; the normal live guards still own the
# next actual turn command.
ready = actual["admitted"] and all(
self.monitor.assess_command_support(0, rate, terrain, pose, height)["admitted"]
and self.monitor.regulate_command(0, rate, terrain, pose)[2] == 1
for rate in (-0.1, 0.1)
)
if ready:
self.active = None
self.transition = "turn-placement-observed-ready"
return False
return admitted