Files
VSAG_SENTRY_SIM_27RMUL/tools/_internal/arena_grid.py
T

153 lines
6.6 KiB
Python

"""Static arena clearance and deterministic routes for isolated simulation tests."""
from collections import deque
from functools import cache
import heapq
import math
from pathlib import Path
import numpy as np
import yaml
START = (-5.0, 3.0)
SURVEY_GOALS = ((-5., 0.), (-5., -3.), (0., -3.), (5., -3.), (5., 0.), (5., 3.),
(0., 3.), (0., 0.), (0., -3.), (-5., -3.), START)
# Revisit the reported east route in both directions before covering the perimeter.
ARENA_GOALS = ((0., 0.), (5., -3.), (0., 0.), (5., -3.), (5., 0.), (5., 3.),
(0., 3.), START, (-5., 0.), (-5., -3.), (0., -3.), (0., 0.), START)
class ArenaGrid:
def __init__(self, map_yaml):
path = Path(map_yaml)
config = yaml.safe_load(path.read_text())
self.resolution = float(config['resolution'])
self.origin = tuple(config['origin'][:2])
if config.get('mode', 'trinary') != 'trinary' or config['origin'][2] != 0:
raise ValueError('arena coverage expects an unrotated trinary occupancy map')
with (path.parent / config['image']).open('rb') as image:
def header():
line = image.readline().split(b'#', 1)[0].strip()
while not line:
raw = image.readline()
if not raw:
raise ValueError('truncated PGM header')
line = raw.split(b'#', 1)[0].strip()
return line
if header() != b'P5':
raise ValueError('expected binary PGM occupancy map')
width, height = map(int, header().split())
if header() != b'255':
raise ValueError('expected 8-bit PGM occupancy map')
pixels = np.frombuffer(image.read(), dtype=np.uint8).reshape(height, width)
self.size = (height, width)
probability = pixels / 255 if config.get('negate', 0) else 1 - pixels / 255
self.free = (probability < config['free_thresh'])[::-1]
def cell(self, point):
x, y = point
return (math.floor((y-self.origin[1])/self.resolution),
math.floor((x-self.origin[0])/self.resolution))
def point(self, cell):
y, x = cell
return (self.origin[0]+(x+0.5)*self.resolution,
self.origin[1]+(y+0.5)*self.resolution)
def neighbors(self, cell):
y, x = cell
h, w = self.size
for i, j in ((y-1,x),(y+1,x),(y,x-1),(y,x+1)):
if 0 <= i < h and 0 <= j < w:
yield i, j
@cache
def clear(self, clearance):
radius = math.ceil(clearance/self.resolution)
padded = np.pad(self.free, radius)
h, w = self.size
mask = self.free.copy()
for y in range(-radius, radius+1):
for x in range(-radius, radius+1):
if math.hypot(x, y)*self.resolution <= clearance + 1e-10:
mask &= padded[radius+y:radius+y+h, radius+x:radius+x+w]
return mask
def coverage(self):
# 外接半径:footprint 现在是 0.61 x 0.61 的正方形(要覆盖云台 yaw 扫掠圆,
# 半径 0.3021 m),外接半径 = 0.305 * sqrt(2)。
travel = self.clear(math.hypot(0.305, 0.305))
start = self.cell(START)
if not travel[start]:
raise ValueError('spawn pose fails the footprint clearance check')
connected = np.zeros(self.size, dtype=bool)
connected[start] = True
queue = deque([start])
while queue:
for cell in self.neighbors(queue.popleft()):
if travel[cell] and not connected[cell]:
connected[cell] = True
queue.append(cell)
targets = connected & self.clear(0.50)
wide = self.clear(0.65)
tiles = {}
for cell in zip(*np.nonzero(targets)):
point = self.point(cell)
grid = tuple(map(math.floor, point))
score = (not wide[cell], math.dist(point, (grid[0]+0.5, grid[1]+0.5)), point)
if grid not in tiles or score < tiles[grid]:
tiles[grid] = score
ys, xs = np.nonzero(connected)
return {'reachable_cells': int(connected.sum()), 'eligible_goal_cells': int(targets.sum()),
'reachable_area_m2': float(connected.sum() * self.resolution**2),
'center_coordinate_bounds_m': [self.point((min(ys), min(xs))),
self.point((max(ys), max(xs)))],
'disconnected_goal_cells': int((self.clear(0.50)&~connected).sum()),
'resolution_m': self.resolution,
'samples': [tiles[tile][2] for tile in sorted(tiles)]}
def route(self, anchors, clearance=0.55):
safe = self.clear(clearance)
points = [START]
for target in anchors:
start, end = self.cell(points[-1]), self.cell(target)
if not safe[start] or not safe[end]:
raise ValueError(f'unsafe survey anchor {points[-1]} -> {target}')
frontier = [(0, 0, start)]
distance = {start: 0}
previous = {}
while frontier:
_, cost, node = heapq.heappop(frontier)
if node == end:
break
if cost != distance[node]:
continue
for cell in self.neighbors(node):
if safe[cell] and cost+1 < distance.get(cell, math.inf):
distance[cell] = cost+1
previous[cell] = node
estimate = abs(cell[0]-end[0])+abs(cell[1]-end[1])
heapq.heappush(frontier, (cost+1+estimate, cost+1, cell))
else:
raise ValueError(f'no survey route from {points[-1]} to {target}')
cells = [end]
while cells[-1] != start:
cells.append(previous[cells[-1]])
candidates = [self.point(c) for c in reversed(cells[1:-1])] + [target]
index = 0
while index < len(candidates):
a = points[-1]
# Advance to the furthest visible waypoint along the grid path.
for last in range(len(candidates)-1, index-1, -1):
b = candidates[last]
count = max(1, math.ceil(2*math.dist(a,b)/self.resolution))
if all(safe[self.cell(tuple(x+(y-x)*i/count for x,y in zip(a,b)))]
for i in range(count+1)):
break
else:
raise ValueError(f'unable to simplify survey route near {a}')
points.append(b)
index = last+1
return points[1:]