117 lines
5.4 KiB
Python
117 lines
5.4 KiB
Python
"""Make a Gazebo-only map from stationary LiDAR scans at commanded survey stations."""
|
|
|
|
import csv
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import struct
|
|
import tempfile
|
|
|
|
import numpy as np
|
|
|
|
import project_env
|
|
from _internal.arena_grid import START, SURVEY_GOALS
|
|
|
|
SETTLE_SECONDS = 0.8
|
|
STATION_SECONDS = 1.5
|
|
MAP_RESOLUTION = 0.10
|
|
|
|
|
|
def stations(grid):
|
|
result = [START]
|
|
route = grid.route(SURVEY_GOALS)
|
|
for a, b in zip([START] + route, route):
|
|
steps = max(1, math.ceil(math.dist(a, b) / 1.5))
|
|
for i in range(1, steps + 1):
|
|
point = tuple(round(x + (y - x) * i / steps, 4) for x, y in zip(a, b))
|
|
if point not in result:
|
|
result.append(point)
|
|
return result
|
|
|
|
|
|
def set_station(gz, point, partition):
|
|
x, y = point
|
|
request = f'name: "sentry" position: {{ x: {x} y: {y} z: 0 }} orientation: {{ w: 1 }}'
|
|
response = project_env.run_gz(
|
|
gz, 'service', '-s', '/world/rmul_arena/set_pose', '--reqtype', 'gz.msgs.Pose',
|
|
'--reptype', 'gz.msgs.Boolean', '--timeout', '2000', '--req', request,
|
|
timeout=3, partition=partition,
|
|
)
|
|
if response.returncode or not re.search(r'^data:\s*true\s*$', response.stdout, re.M):
|
|
raise RuntimeError(f'Gazebo did not acknowledge station {point}: {response.stdout} {response.stderr}')
|
|
|
|
|
|
def transform(points, pose):
|
|
translation, xyz, w = pose[:3], pose[3:6], pose[6]
|
|
twice = 2 * np.cross(xyz, points)
|
|
return points + w * twice + np.cross(xyz, twice) + translation
|
|
|
|
|
|
def selected_clouds(directory, survey):
|
|
with (directory / 'scans.csv').open() as stream:
|
|
scans = [(float(row['timestamp']), row['file']) for row in csv.DictReader(stream)]
|
|
for station in survey:
|
|
stamp = station['command_time']
|
|
candidates = [scan for scan in scans if stamp + SETTLE_SECONDS <= scan[0] < stamp + STATION_SECONDS]
|
|
if len(candidates) < 3:
|
|
raise RuntimeError(f'insufficient settled scans at {station["goal"]}')
|
|
yield station['goal'], candidates[len(candidates) // 2]
|
|
|
|
|
|
def build_map(directory, selected, output):
|
|
config = (directory / 'config.txt').read_text().splitlines()
|
|
extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]]
|
|
if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']:
|
|
raise ValueError('survey recorder configuration is missing LiDAR extrinsics')
|
|
bounds_rows = [row.split()[1:] for row in config if row.startswith('map_bounds ')]
|
|
if len(bounds_rows) != 1 or len(bounds_rows[0]) != 6:
|
|
raise ValueError('survey recorder configuration is missing map bounds')
|
|
low, high = np.array(bounds_rows[0], dtype=float).reshape(2, 3)
|
|
if not np.isfinite([low, high]).all() or not (low < high).all():
|
|
raise ValueError('survey recorder configuration has invalid map bounds')
|
|
clouds = []
|
|
for (x, y), (stamp, filename) in selected:
|
|
raw = (directory / filename).read_bytes()
|
|
magic, version, time, count = struct.unpack_from('<8sIdI', raw)
|
|
if magic != b'FLPC0001' or version != 1 or time != stamp or len(raw) != 24 + count * 24:
|
|
raise ValueError(f'invalid recorded scan {filename}')
|
|
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
|
|
points = rows['point'][:, :3].astype(np.float64)
|
|
base_from_imu, imu_from_lidar = extrinsics
|
|
points = points[np.isfinite(points).all(axis=1)]
|
|
world = transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0]
|
|
selected_points = world[((world >= low) & (world <= high)).all(axis=1)]
|
|
if not len(selected_points):
|
|
raise RuntimeError(f'no in-field returns at station {(x, y)}')
|
|
clouds.append(selected_points)
|
|
points = np.concatenate(clouds)
|
|
# Average measured returns that occupy the same voxel across overlapping views.
|
|
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
|
|
_, bins, counts = np.unique(grid, axis=0, return_inverse=True, return_counts=True)
|
|
centers = np.column_stack([np.bincount(bins, weights=axis) / counts for axis in points.T])
|
|
with tempfile.NamedTemporaryFile(dir=output.parent) as stream:
|
|
stream.write(struct.pack('<8sIdQ', b'FLMAP001', 1, MAP_RESOLUTION, len(centers)))
|
|
stream.write(centers.astype('<f8').tobytes())
|
|
stream.flush()
|
|
os.link(stream.name, output)
|
|
return len(centers)
|
|
|
|
|
|
def evaluate_stations(directory, selected):
|
|
# Independent truth is read only after all scan selections have been made.
|
|
truth = np.loadtxt(directory / 'truth.tum', ndmin=2)
|
|
report = []
|
|
for (x, y), (stamp, filename) in selected:
|
|
index = int(np.argmin(np.abs(truth[:, 0] - stamp)))
|
|
time, *pose = truth[index]
|
|
if abs(time - stamp) > 0.025:
|
|
raise RuntimeError(f'no independent truth for {filename} at {stamp:.3f}s')
|
|
error = math.dist(pose[:3], (x, y, 0))
|
|
rotation = math.degrees(2 * math.acos(min(1.0, abs(pose[6]))))
|
|
report.append({'station': [x, y], 'timestamp': stamp, 'scan': filename,
|
|
'position_error_m': error, 'rotation_error_deg': rotation})
|
|
(directory / 'survey_truth.json').write_text(json.dumps(report, indent=2))
|
|
if any(row['position_error_m'] > 0.02 or row['rotation_error_deg'] > 1 for row in report):
|
|
raise RuntimeError('commanded poses failed independent survey verification; see survey_truth.json')
|