Files
RC2027_BR_code/minco_ws/docs/diagnostics/analyze_map_acceptance.py
T

416 lines
17 KiB
Python
Raw Normal View History

#!/usr/bin/python3
"""Read-only map acceptance for a static bag (revision 2).
Revision 2 withdraws two earlier claims:
* "a 0.62 m circular inflation explains the occupied body centre" -- the
active model is a ROTATED RECTANGLE footprint (SAT test) with separate up /
down z inflation. The circular story was wrong even though the numbers
happened to fit.
* "a 3.65 m continuous surface closes the path 3.7-4.0 m ahead" -- that came
from clustering cells after projecting across x and z. Cross-sections are
now reported independently, at the query height only.
Questions answered:
1. how many frames have the cell at the body-centre height occupied?
2. which raw cells can geometrically cover the body centre, given the real
footprint, its orientation and the up/down inflation range? Reported as
CANDIDATES; no unique cause is claimed.
3. what do independent cross-sections at the query height look like 3.7-4.0 m
ahead, in raw and inflated layers separately?
Rules honoured: an absent cell is "not observed / not inflated", never free;
the display height band is a viewing choice, not a measured body half height;
nothing here claims which physical surface produced a return.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from collections import Counter
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import analyze_pose_jitter as pj # load_odom, read_metadata
import analyze_self_boundary as sb # cloud_fields, _stamp_ns
CELL = 0.05
ODOM_MATCH_TOL_S = 0.030
# From planner_vehicle.yaml (z up/down) and the bringup footprint measurement.
# rebuildInflationOffsets() takes the rectangle branch, so the inflation shape is
# the padded footprint, not a disc.
FOOTPRINT_LENGTH = 0.81
FOOTPRINT_WIDTH = 0.80
FOOTPRINT_MARGIN = 0.09
FOOTPRINT_YAW_TOL = 0.035
Z_UP = 0.15
Z_DOWN = 0.05
FORWARD_XS = (3.70, 3.80, 3.90, 4.00)
QUERY_HALF_Z = CELL / 2 + 1e-9
def yaw_from_quat(q):
x, y, z, w = q
return math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
def rect_intersects(x, y, yaw, half_length, half_width, cell_half):
"""Same SAT test as plan_env/rectangular_footprint.h."""
c, s = math.cos(yaw), math.sin(yaw)
ac, as_ = abs(c), abs(s)
return (abs(x) <= half_length * ac + half_width * as_ + cell_half + 1e-10 and
abs(y) <= half_length * as_ + half_width * ac + cell_half + 1e-10 and
abs(c * x + s * y) <= half_length + cell_half * (ac + as_) + 1e-10 and
abs(-s * x + c * y) <= half_width + cell_half * (ac + as_) + 1e-10)
def discrete_inflate_offsets(yaw, res):
"""The integer cell offsets md_.inflate_offsets_ would hold for this yaw.
rebuildInflationOffsets() loops over integer cells x, y in [-n, n], keeps the
ones whose SAT test hits, and for each keeps z in [-down, +up] cells. Marking
is therefore a discrete offset lookup, not continuous containment.
"""
a = 0.5 * FOOTPRINT_LENGTH + FOOTPRINT_MARGIN
b = 0.5 * FOOTPRINT_WIDTH + FOOTPRINT_MARGIN
pad = 2.0 * math.hypot(a, b) * math.sin(0.5 * min(abs(FOOTPRINT_YAW_TOL), math.pi))
n = int(math.ceil((math.hypot(a + pad, b + pad) + res) / res))
up = int(math.ceil(Z_UP / res))
down = int(math.ceil(Z_DOWN / res))
offsets = set()
for ix in range(-n, n + 1):
for iy in range(-n, n + 1):
if rect_intersects(ix * res, iy * res, yaw, a + pad, b + pad, res):
for iz in range(-down, up + 1):
offsets.add((ix, iy, iz))
return offsets, n, up, down, a + pad, b + pad, pad
def inflation_half_extents():
a = 0.5 * FOOTPRINT_LENGTH + FOOTPRINT_MARGIN
b = 0.5 * FOOTPRINT_WIDTH + FOOTPRINT_MARGIN
pad = 2.0 * math.hypot(a, b) * math.sin(0.5 * min(abs(FOOTPRINT_YAW_TOL), math.pi))
return a + pad, b + pad, pad
def load_cloud_frames(bag_dir: Path, topic: str):
meta = pj.read_metadata(bag_dir)
if topic not in meta["topics"]:
raise SystemExit(f"topic {topic} not in bag")
deserialize_message, get_message = pj._load_ros()
for path in meta["files"]:
conn = pj._open_shard(path)
try:
rows = conn.execute("SELECT id, name, type FROM topics").fetchall()
found = [(i, t) for i, n, t in rows if n == topic]
if not found:
continue
topic_id, kind = found[0]
cls = get_message(kind)
for (blob,) in conn.execute(
"SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp",
(topic_id,)):
msg = deserialize_message(blob, cls)
f = sb.cloud_fields(msg)
xyz = np.column_stack([f["x"], f["y"], f["z"]]).astype(np.float64)
xyz = xyz[np.isfinite(xyz).all(axis=1)]
yield sb._stamp_ns(msg.header.stamp), xyz
finally:
conn.close()
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--bag", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
odom = pj.load_odom(args.bag, "/body_odom")
stamps = np.asarray(odom["stamp_ns"], dtype=np.int64)
order = np.argsort(stamps)
stamps = stamps[order]
pos = np.asarray(odom["position"], dtype=np.float64)[order]
quat = np.asarray(odom["quaternion"], dtype=np.float64)[order]
yaws = np.array([yaw_from_quat(q) for q in quat])
def nearest_odom(stamp):
i = int(np.searchsorted(stamps, stamp))
best = None
for cand in (i - 1, i, i + 1):
if 0 <= cand < len(stamps):
gap = abs(int(stamps[cand]) - int(stamp)) / 1e9
if gap <= ODOM_MATCH_TOL_S and (best is None or gap < best[0]):
best = (gap, cand)
return best
inflate_frames = list(load_cloud_frames(args.bag, "/grid_map/occupancy_inflate"))
raw_by_stamp = dict(load_cloud_frames(args.bag, "/grid_map/occupancy"))
raw_stamps = np.asarray(sorted(raw_by_stamp), dtype=np.int64)
def nearest_raw(stamp, tol_s=0.25):
if raw_stamps.size == 0:
return None
i = int(np.searchsorted(raw_stamps, stamp))
best = None
for cand in (i - 1, i, i + 1):
if 0 <= cand < len(raw_stamps):
gap = abs(int(raw_stamps[cand]) - int(stamp)) / 1e9
if gap <= tol_s and (best is None or gap < best[0]):
best = (gap, int(raw_stamps[cand]))
return None if best is None else best
half_len, half_wid, pad = inflation_half_extents()
matched = 0
occupied = 0
centre_z = []
candidate_sides = Counter()
frames_with_candidates = 0
candidate_counts = []
candidate_xy = []
samples = []
for stamp, infl in inflate_frames:
hit = nearest_odom(stamp)
if hit is None:
continue
matched += 1
centre = pos[hit[1]]
yaw = yaws[hit[1]]
centre_z.append(float(centre[2]))
same_xy = (np.abs(infl[:, 0] - centre[0]) <= CELL / 2 + 1e-9) & \
(np.abs(infl[:, 1] - centre[1]) <= CELL / 2 + 1e-9)
same_z = np.abs(infl[:, 2] - centre[2]) <= QUERY_HALF_Z
if not (same_xy & same_z).any():
continue
occupied += 1
near = nearest_raw(stamp)
if near is None:
samples.append({"stamp_ns": int(stamp), "candidates": None})
continue
raw = raw_by_stamp[near[1]]
offsets = discrete_inflate_offsets(yaw, CELL)[0]
# centre_cell = raw_cell + offset, so the offset that would produce the
# body-centre cell from this raw cell is (centre - raw) / resolution.
idx = np.rint((centre[None, :] - raw) / CELL).astype(np.int64)
inside = np.fromiter(
(tuple(v) in offsets for v in idx), dtype=bool, count=len(raw))
cand = raw[inside]
candidate_counts.append(len(cand))
if len(cand):
frames_with_candidates += 1
c, s = math.cos(yaw), math.sin(yaw)
bx = c * (cand[:, 0] - centre[0]) + s * (cand[:, 1] - centre[1])
by = -s * (cand[:, 0] - centre[0]) + c * (cand[:, 1] - centre[1])
candidate_xy.extend(zip(bx.tolist(), by.tolist()))
for x_b in bx:
if x_b < -0.5 * FOOTPRINT_LENGTH:
candidate_sides["rear"] += 1
elif x_b > 0.5 * FOOTPRINT_LENGTH:
candidate_sides["front"] += 1
else:
candidate_sides["lateral_or_under"] += 1
if len(samples) < 30:
samples.append({
"stamp_ns": int(stamp),
"raw_stamp_gap_s": near[0],
"candidates": int(len(cand)),
"candidate_body_xy": np.round(
np.column_stack([bx, by]), 3).tolist()[:8],
})
# ---- independent cross-sections --------------------------------------
cross = {}
last_stamp = inflate_frames[-1][0]
hit = nearest_odom(last_stamp)
if hit is not None:
centre = pos[hit[1]]
yaw = yaws[hit[1]]
near = nearest_raw(last_stamp)
raw = raw_by_stamp[near[1]] if near else np.zeros((0, 3))
infl = inflate_frames[-1][1]
c, s = math.cos(yaw), math.sin(yaw)
def to_body(arr):
dx = arr[:, 0] - centre[0]
dy = arr[:, 1] - centre[1]
return np.column_stack([c * dx + s * dy, -s * dx + c * dy, arr[:, 2]])
body_raw = to_body(raw) if len(raw) else np.zeros((0, 3))
body_infl = to_body(infl)
body_raw = body_raw[np.abs(body_raw[:, 2] - centre[2]) <= QUERY_HALF_Z]
body_infl = body_infl[np.abs(body_infl[:, 2] - centre[2]) <= QUERY_HALF_Z]
for x0 in FORWARD_XS:
sel_r = body_raw[np.abs(body_raw[:, 0] - x0) <= CELL / 2 + 1e-9]
sel_i = body_infl[np.abs(body_infl[:, 0] - x0) <= CELL / 2 + 1e-9]
cross[f"{x0:.2f}"] = {
"raw_y": sorted({round(float(v), 2) for v in sel_r[:, 1]}),
"inflate_y": sorted({round(float(v), 2) for v in sel_i[:, 1]}),
"raw_count": int(len(sel_r)),
"inflate_count": int(len(sel_i)),
}
summary = {
"revision": 3,
"superseded_approximations": {
"note": "candidate counts reported before this revision used "
"continuous containment and a 0.80 m length; they are "
"approximate and are replaced by the discrete-offset numbers "
"below",
"old_candidate_count_p50": 3,
"old_candidate_count_max": 7,
"old_total_candidates": 2139,
},
"withdrawn": [
"0.62 m circular inflation explains the occupied body centre",
"a 3.65 m continuous surface closes the path 3.7-4.0 m ahead",
],
"bag": str(args.bag),
"model": {
"source": "plan_env/src/grid_map.cpp rebuildInflationOffsets() "
"rectangle branch; plan_env/rectangular_footprint.h",
"footprint_length_m": FOOTPRINT_LENGTH,
"footprint_width_m": FOOTPRINT_WIDTH,
"footprint_margin_m": FOOTPRINT_MARGIN,
"footprint_yaw_tolerance_rad": FOOTPRINT_YAW_TOL,
"angular_padding_m": pad,
"inflate_half_extents_m": [half_len, half_wid],
"marking_rule": "discrete integer cell offsets computed by the same "
"SAT loop as rebuildInflationOffsets(); membership "
"test, not continuous containment",
"z_up_m": Z_UP,
"z_down_m": Z_DOWN,
},
"query": {
"cell_size_m": CELL,
"body_centre_height_m": {
"p05": float(np.quantile(centre_z, 0.05)) if centre_z else None,
"p50": float(np.quantile(centre_z, 0.50)) if centre_z else None,
"p95": float(np.quantile(centre_z, 0.95)) if centre_z else None,
},
"occupied_test": "inflated cell within one cell of the body-centre XY "
"and in the same z layer",
},
"q1_body_centre": {
"inflate_messages": len(inflate_frames),
"matched_to_body_odom": matched,
"occupied_frames": occupied,
"occupied_fraction": (occupied / matched) if matched else None,
},
"q2_candidates": {
"rule": "raw cells whose offset falls inside the rotated footprint "
"and whose z lies in [centre_z - z_up, centre_z + z_down]",
"frames_with_footprint_candidates": frames_with_candidates,
"frames_checked": occupied,
"frames_without_any_candidate": occupied - frames_with_candidates,
"candidate_count_p50": float(np.median(candidate_counts))
if candidate_counts else None,
"candidate_count_max": int(max(candidate_counts)) if candidate_counts else None,
"candidate_body_xy_p50": [float(np.median([v[0] for v in candidate_xy])),
float(np.median([v[1] for v in candidate_xy]))]
if candidate_xy else None,
"candidate_body_xy_p05_p95": [
[float(np.quantile([v[0] for v in candidate_xy], 0.05)),
float(np.quantile([v[0] for v in candidate_xy], 0.95))],
[float(np.quantile([v[1] for v in candidate_xy], 0.05)),
float(np.quantile([v[1] for v in candidate_xy], 0.95))]]
if candidate_xy else None,
"side_counts": dict(candidate_sides),
"note": "candidate sources only; the map does not record which raw "
"cell produced a given inflated cell",
"samples": samples,
},
"q3_cross_sections": {
"rule": "independent slice at each x in the body frame, using only "
"cells at the body-centre z layer; no aggregation across x or z",
"sections": cross,
},
"limits": [
"An absent cell means not observed or not inflated, never free.",
"The z band used for viewing is a display choice; it is not a "
"measured body half height and it does not establish that the "
"ground was excluded.",
"The body centre height comes from /body_odom, which is an estimate.",
"Attribution lists candidates by geometry only.",
"The map is built with the estimator's own pose; a pose bias shifts "
"the map with it.",
],
}
(args.output / "summary.json").write_text(
json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
print(json.dumps({k: summary[k] for k in ("q1_body_centre", "q2_candidates")},
indent=2, ensure_ascii=False))
print("cross-sections:", json.dumps(cross, ensure_ascii=False))
# ---- figure: query-height overhead + independent cross-sections -------
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except Exception as exc: # pragma: no cover
print(f"[warn] matplotlib unavailable: {exc}", file=sys.stderr)
return 0
fig = plt.figure(figsize=(14, 8))
gs = fig.add_gridspec(1, 2, width_ratios=[1.5, 1.0])
ax = fig.add_subplot(gs[0, 0])
ax.scatter(body_raw[:, 0], body_raw[:, 1], s=9, c="#1f77b4",
label="raw (query height)")
ax.scatter(body_infl[:, 0], body_infl[:, 1], s=2, c="#d62728", alpha=0.30,
label="inflated (query height)")
ax.add_patch(plt.Rectangle((-0.5 * FOOTPRINT_LENGTH, -0.5 * FOOTPRINT_WIDTH),
FOOTPRINT_LENGTH, FOOTPRINT_WIDTH,
fill=False, ec="black", lw=1.5, label="footprint"))
for x0 in FORWARD_XS:
ax.axvline(x0, color="orange", ls="--", lw=0.8)
ax.set_xlim(-2, 5)
ax.set_ylim(-2.5, 3.5)
ax.set_xlabel("x forward [m]")
ax.set_ylabel("y left [m]")
ax.set_title("query-height slice (body frame)")
ax.grid(alpha=0.3)
ax.legend(fontsize=7, loc="upper right")
right = gs[0, 1].subgridspec(len(FORWARD_XS), 1, hspace=0.55)
for i, x0 in enumerate(FORWARD_XS):
s_ax = fig.add_subplot(right[i])
data = cross.get(f"{x0:.2f}", {})
raw_y = data.get("raw_y", [])
infl_y = data.get("inflate_y", [])
if raw_y:
s_ax.plot(raw_y, np.ones(len(raw_y)), "|", ms=12, color="#1f77b4")
if infl_y:
s_ax.plot(infl_y, np.full(len(infl_y), 0.4), "|", ms=12, color="#d62728")
s_ax.set_ylim(0, 1.3)
s_ax.set_yticks([1.0, 0.4])
s_ax.set_yticklabels(["raw", "infl"], fontsize=7)
s_ax.set_title(f"x = {x0:.2f} m raw {data.get('raw_count',0)} / "
f"inflated {data.get('inflate_count',0)}", fontsize=8)
s_ax.grid(alpha=0.25, axis="x")
if i == len(FORWARD_XS) - 1:
s_ax.set_xlabel("y left [m]")
else:
s_ax.set_xticklabels([])
fig.suptitle("Independent cross-sections at the body-centre height "
"(no cross-x or cross-z projection)")
fig.tight_layout()
fig.savefig(args.output / "cross_sections.png", dpi=140)
plt.close(fig)
print(f"figure -> {args.output / 'cross_sections.png'}")
return 0
if __name__ == "__main__":
raise SystemExit(main())