Files
VSAG_SENTRY_SIM_27RMUL/tools/free_goals.py
T

223 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""从栅格图里找出「车能安全通过」的目标点,并检查从起点连不连得过去。
用法::
python3 tools/free_goals.py # 起点默认 (-5.0, 3.0) 当前出生点
python3 tools/free_goals.py --from 0.0 0.0 # 换个起点(场地中心)
python3 tools/free_goals.py --min-clear 0.7 # 要求更大净空
python3 tools/free_goals.py --map path/to/x.yaml
不依赖 ROS,直接读官方迁移包里的 yaml + pgm,可以随时跑。
为什么需要这个:RMUL 2027 的官方栅格图是 CAD 的「保守障碍投影」,
场内有两块 0.4 m 高的障碍把场地切成几条走廊,很多看起来很空的点
(比如 (3.0, 4.0))其实压在障碍里,发过去必然规划失败。
"""
import argparse
import collections
import math
import pathlib
import re
import sys
import numpy as np
# 车体 0.65 x 0.54 矩形,半对角 0.422 m。
HALF_DIAGONAL = 0.422
# 默认要求的净空。
DEFAULT_MIN_CLEAR = 0.50
# 占据判定阈值,和 yaml 的 occupied_thresh 对齐。
OCCUPIED_THRESHOLD = 65
DEFAULT_YAML = (
'field/RMUL2027_map_transfer_20261016_STEP_R1'
'/src/guodong_sentry_sim/maps/rmul_2027/rmul_2027.yaml')
_NEIGHBORS = ((1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0),
(1, 1, math.sqrt(2)), (1, -1, math.sqrt(2)),
(-1, 1, math.sqrt(2)), (-1, -1, math.sqrt(2)))
def read_pgm(path):
"""读二进制 PGM(P5),返回 (像素数组, 宽, 高, 最大值)。"""
raw = path.read_bytes()
i, fields = 0, []
while len(fields) < 4:
while raw[i:i + 1].isspace():
i += 1
if raw[i:i + 1] == b'#':
while raw[i:i + 1] not in (b'\n', b''):
i += 1
continue
start = i
while not raw[i:i + 1].isspace():
i += 1
fields.append(raw[start:i])
i += 1
width, height, maxval = int(fields[1]), int(fields[2]), int(fields[3])
img = np.frombuffer(raw[i:i + width * height], dtype=np.uint8)
return img.reshape(height, width), width, height, maxval
def load_map(yaml_path):
"""读 yaml + pgm,返回占据布尔表和地图元信息(行 0 = y 最小)。"""
yaml_path = pathlib.Path(yaml_path)
text = yaml_path.read_text()
res = float(re.search(r'resolution:\s*([\d.]+)', text).group(1))
ox, oy = [float(v) for v in
re.search(r'origin:\s*\[([^\]]+)\]', text).group(1).split(',')[:2]]
image = re.search(r'image:\s*(\S+)', text).group(1).strip('"\'')
occ_thresh = float(re.search(r'occupied_thresh:\s*([\d.]+)', text).group(1))
img, width, height, maxval = read_pgm(yaml_path.parent / image)
# mode: trinary + negate 0 -> 灰度越黑越占据;pgm 行 0 在顶部,翻转成 y 向上。
occupied = (img[::-1, :] <= (1.0 - occ_thresh) * maxval)
return {'arr': occupied, 'res': res, 'ox': ox, 'oy': oy,
'w': width, 'h': height}
def clearance_map(mp):
"""8 邻域 Dijkstra 求每个栅格到最近障碍的距离(米)。"""
import heapq
arr, res = mp['arr'], mp['res']
h, w = arr.shape
dist = np.full((h, w), np.inf)
pq = []
for r, c in zip(*np.nonzero(arr)):
dist[r, c] = 0.0
pq.append((0.0, int(r), int(c)))
heapq.heapify(pq)
while pq:
d, r, c = heapq.heappop(pq)
if d > dist[r, c]:
continue
for dr, dc, weight in _NEIGHBORS:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w:
nd = d + weight
if nd < dist[nr, nc]:
dist[nr, nc] = nd
heapq.heappush(pq, (nd, nr, nc))
return dist * res
def reachable(clear, mp, start, min_clear):
"""从 start 出发,在「净空 >= min_clear」的格子里做 4 邻域连通填充。"""
arr, res, ox, oy = mp['arr'], mp['res'], mp['ox'], mp['oy']
h, w = arr.shape
r0 = int(round((start[1] - oy) / res))
c0 = int(round((start[0] - ox) / res))
# 起点自己不够干净时,就近找一个达标的种子格。
if not (0 <= r0 < h and 0 <= c0 < w):
raise SystemExit(f'起点 {start} 在地图外')
if clear[r0, c0] < min_clear:
best = None
for dr in range(-40, 41):
for dc in range(-40, 41):
r, c = r0 + dr, c0 + dc
if 0 <= r < h and 0 <= c < w and clear[r, c] >= min_clear:
dd = dr * dr + dc * dc
if best is None or dd < best[0]:
best = (dd, r, c)
if best is None:
raise SystemExit(f'起点 {start} 周围 1 m 内没有安全格子')
r0, c0 = best[1], best[2]
ok = clear >= min_clear
seen = np.zeros_like(ok)
seen[r0, c0] = True
queue = collections.deque([(r0, c0)])
while queue:
r, c = queue.popleft()
for dr, dc, _ in _NEIGHBORS:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and ok[nr, nc] and not seen[nr, nc]:
seen[nr, nc] = True
queue.append((nr, nc))
return seen, (r0, c0)
def main():
"""打印可达的安全目标点,并画一张安全通行走廊图。"""
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--map', default=DEFAULT_YAML, help='栅格图 yaml 路径')
ap.add_argument('--from', dest='start', nargs=2, type=float,
default=[-5.0, 3.0], metavar=('X', 'Y'), help='起点 map 坐标')
ap.add_argument('--min-clear', type=float, default=DEFAULT_MIN_CLEAR,
help=f'要求的最小净空(米),默认 {DEFAULT_MIN_CLEAR}')
ap.add_argument('--grid', type=float, default=0.5,
help='候选点采样间隔(米),默认 0.5')
ap.add_argument('--no-map', action='store_true', help='不画 ASCII 图')
args = ap.parse_args()
mp = load_map(args.map)
clear = clearance_map(mp)
res, ox, oy = mp['res'], mp['ox'], mp['oy']
print(f'地图 {mp["w"]}x{mp["h"]} @ {res} m/px origin=({ox}, {oy})')
print(f'车体半对角 {HALF_DIAGONAL:.3f} m,要求净空 >= {args.min_clear:.2f} m')
print(f'起点 ({args.start[0]:.2f}, {args.start[1]:.2f})')
seen, seed = reachable(clear, mp, args.start, args.min_clear)
sx, sy = ox + seed[1] * res, oy + seed[0] * res
area = seen.sum() * res * res
print(f'从起点连通的安全区面积: {area:.1f} m²\n')
step = max(1, int(round(args.grid / res)))
cands = []
h, w = clear.shape
for r in range(0, h, step):
for c in range(0, w, step):
if seen[r, c]:
x, y = ox + (c + 0.5) * res, oy + (r + 0.5) * res
if 0.0 <= x <= 12.0 and 0.0 <= y <= 8.0:
cands.append((x, y, clear[r, c]))
# 贪心去重:任意两点至少隔开 1.2 m,避免刷一屏相邻点。
picked = []
for x, y, cl in sorted(cands, key=lambda t: -t[2]):
if all(math.hypot(x - px, y - py) > 1.2 for px, py, _ in picked):
picked.append((x, y, cl))
picked.sort(key=lambda t: math.hypot(t[0] - sx, t[1] - sy))
print(f'{"目标点 (map)":>20} {"净空":>6} {"离起点":>7} field 坐标')
print(' ' + '-' * 62)
for x, y, cl in picked:
d = math.hypot(x - sx, y - sy)
print(f' ({x:5.2f}, {y:4.2f}) {cl:5.2f} m {d:6.2f} m '
f'({x - 6.0:5.2f}, {y - 4.0:5.2f})')
print('\n直接复制就能跑:')
for x, y, cl in picked[:6]:
print(f' build/linux/x86_64/release/nav_client {x:.2f} {y:.2f}')
if args.no_map:
return 0
print('\n=== 安全通行走廊(+ 能过 / . 空但太窄 / # 障碍 / o 起点)===')
stride = 6
print(' ' + ''.join(str(int(ox + c * res) % 10)
for c in range(0, w, stride)))
for r in range(h - 1, -1, -stride):
line = ''
for c in range(0, w, stride):
if (r, c) == seed:
line += 'o'
elif seen[r, c]:
line += '+'
elif mp['arr'][r, c]:
line += '#'
else:
line += '.'
print(f' {oy + r * res:5.2f} {line}')
print(f'\n 每格 {stride * res:.2f} m')
return 0
if __name__ == '__main__':
sys.exit(main())