fix: the arc pose was defined against the sensor, so it followed the robot

The target point was the point on the fitted circle furthest from the sensor,
and yaw was the direction from there back to the sensor. Both are defined
against WHERE YOU ARE STANDING, so the detector always reported that the dock
faces exactly where the robot happens to be. Measured on one fixed cradle from
five positions:

    view offset   0     10     20     30     40  deg
    yaw error   -0.0  -10.0  -20.0  -30.0  -40.0  deg

The yaw error equals the viewing offset exactly, and the target slid along the
arc with it, from (0.400, 0.000) to (0.306, -0.257). Nothing in the log looked
wrong. It surfaced because the goal moved between missions while the cradle had
not been touched.

A CIRCLE has no axis. Only the physical ARC does, and it is the bisector of the
two endpoint radii. fitCircle now reports mid_angle, and the pose comes from
that: target = C + R*(cos mid, sin mid), yaw = mid + pi. Same five positions:

    yaw error   -0.2   -0.2   -0.3   -2.4   -3.9  deg

I had written the old definition up as a feature - stable when part of the arc
is hidden. It was stable, at the wrong value, by not looking at the shape.

The residual at 30-40 degrees is real and has to be gated, not hidden: an
occluded edge moves the observed midpoint, and the measured relationship is
yaw error ~= (true span - observed span) / 2. So arc_span is now checked on
BOTH sides with its own arc_span_tolerance, rather than being an upper bound
borrowing slack from arc_radius_tolerance. Seeing too little of the arc is as
dangerous as seeing too much, and only one of those was being caught.

This reverses the earlier reasoning that copied the V's asymmetric wing rule.
The analogy does not hold: a V's apex and bisector survive one wing being
short because they are intrinsic, and an arc's axis does not exist at all
without both edges.

ThePoseFollowsTheDockNotTheRobot pins it, and pins it by rotating the DOCK, not
the world. The first draft rotated the whole scene about the sensor, which
leaves the sensor-to-dock relationship unchanged and passes under the old
definition too - it guarded nothing. Rotating the dock in place fails the old
code by 20.05 degrees.

RefusesAnArcWithAnEdgeHiddenBecauseTheAxisWouldBeWrong replaces a test that
asserted the opposite. That test was pinning the bug.
This commit is contained in:
2026-08-26 21:09:26 +07:00
parent 791c838da8
commit 00e5f3e2cb
13 changed files with 19740 additions and 53 deletions

3203
doc/fig/arc_concave.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 101 KiB

3292
doc/fig/arc_geometry.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 103 KiB

4162
doc/fig/v_gates.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 136 KiB

2475
doc/fig/v_geometry.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 79 KiB

1909
doc/fig/v_offset.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 61 KiB

4274
doc/fig/v_tape.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 140 KiB

289
doc/gen_fig.py Normal file
View File

@@ -0,0 +1,289 @@
# -*- coding: utf-8 -*-
"""Sinh hinh hoc cho tai lieu dock_pattern_detector. Moi hinh ve tu SO THAT."""
import math, os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Arc, Rectangle, Circle, FancyArrowPatch
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['font.size'] = 9
plt.rcParams['svg.fonttype'] = 'path' # nhung chu thanh duong -> khong phu thuoc font may in
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fig')
INK, ACC, WARN, MUT = '#1b2733', '#1f6feb', '#c9401a', '#7d8996'
GRID = '#dfe4ea'
def save(fig, name):
fig.savefig(os.path.join(OUT, name), format='svg', bbox_inches='tight',
transparent=True)
plt.close(fig)
print(' ', name)
def frame(ax, xlim, ylim, title=None):
ax.set_xlim(*xlim); ax.set_ylim(*ylim); ax.set_aspect('equal')
ax.grid(True, color=GRID, lw=0.5, zorder=0)
for s in ('top', 'right'): ax.spines[s].set_visible(False)
for s in ('left', 'bottom'): ax.spines[s].set_color(MUT)
ax.tick_params(colors=MUT, labelsize=7)
if title: ax.set_title(title, color=INK, fontsize=10, pad=8)
def sensor(ax, x=0, y=0, label='cảm biến\n(gốc frame scan)'):
ax.plot([x], [y], marker='o', ms=7, color=INK, zorder=5)
ax.annotate(label, (x, y), textcoords='offset points', xytext=(6, -22),
fontsize=7.5, color=INK)
def arrow(ax, p, q, color=ACC, lw=1.4, style='-|>', ms=9):
ax.add_patch(FancyArrowPatch(p, q, arrowstyle=style, mutation_scale=ms,
color=color, lw=lw, zorder=6,
shrinkA=0, shrinkB=0))
def dim(ax, p, q, text, off=0.0, color=WARN, fs=8, above=True):
"""Duong kich thuoc hai dau mui ten."""
(x1, y1), (x2, y2) = p, q
dx, dy = x2 - x1, y2 - y1
L = math.hypot(dx, dy) or 1.0
nx, ny = -dy / L * off, dx / L * off
a, b = (x1 + nx, y1 + ny), (x2 + nx, y2 + ny)
ax.add_patch(FancyArrowPatch(a, b, arrowstyle='<|-|>', mutation_scale=7,
color=color, lw=1.0, zorder=6, shrinkA=0, shrinkB=0))
mx, my = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
ax.annotate(text, (mx, my), textcoords='offset points',
xytext=(0, 5 if above else -11), ha='center',
fontsize=fs, color=color, zorder=7)
# =================================================================================================
# CHỮ V
# =================================================================================================
AP, VANG, WL = 2.0, math.pi / 2, 0.30 # đỉnh ở 2 m, mở 90 độ, cánh 0.30 m
HALF = VANG / 2
TIPX, TIPY = AP - WL * math.cos(HALF), WL * math.sin(HALF)
def v_plate(ax, apex=AP, vang=VANG, wl=WL, color=INK, lw=2.6, z=4):
h = vang / 2
tx, ty = apex - wl * math.cos(h), wl * math.sin(h)
ax.plot([apex, tx], [0, ty], color=color, lw=lw, zorder=z, solid_capstyle='round')
ax.plot([apex, tx], [0, -ty], color=color, lw=lw, zorder=z, solid_capstyle='round')
return (tx, ty), (tx, -ty)
def fig_v_geometry():
fig, ax = plt.subplots(figsize=(7.4, 4.3))
frame(ax, (-0.15, 2.45), (-0.75, 0.75))
sensor(ax)
t1, t2 = v_plate(ax)
ax.plot([AP], [0], marker='o', ms=6, color=WARN, zorder=7)
ax.annotate(u'đỉnh (apex)\ngiao điểm HAI ĐƯỜNG đã khớp,\nkhông phải trung điểm hai đầu mút',
(AP, 0), textcoords='offset points', xytext=(10, 26), fontsize=7.5, color=WARN)
# goc dinh
a1 = math.degrees(math.atan2(t1[1], t1[0] - AP))
a2 = math.degrees(math.atan2(t2[1], t2[0] - AP))
ax.add_patch(Arc((AP, 0), 0.30, 0.30, theta1=a1, theta2=a2 + 360, color=ACC, lw=1.3, zorder=6))
ax.annotate(u'vertex_angle\n= 1.5708 rad (90°)', (AP - 0.17, 0),
textcoords='offset points', xytext=(-96, -6), fontsize=8, color=ACC)
dim(ax, (AP, 0), t1, u'wing_length = 0.30 m', off=0.075)
# phan giac -> yaw
arrow(ax, (AP, 0), (AP - 0.55, 0), color='#0d8050', lw=1.8)
ax.annotate(u'yaw = phân giác, hướng RA phía cảm biến',
(AP - 0.55, 0), textcoords='offset points', xytext=(-16, 12),
fontsize=8, color='#0d8050', ha='right')
# offset -> dich
gx = AP - 0.95
ax.plot([gx], [0], marker='*', ms=15, color='#7b3fbf', zorder=7)
dim(ax, (AP, 0), (gx, 0), u'offset_x = 0.95 m', off=-0.30, color='#7b3fbf', above=False)
ax.annotate(u'pose ĐÍCH ghi ra `dock_target`\n(pose của base_link, KHÔNG phải mép robot)',
(gx, 0), textcoords='offset points', xytext=(-6, -50), fontsize=7.5,
color='#7b3fbf', ha='center')
save(fig, 'v_geometry.svg')
def fig_v_gates():
fig, axs = plt.subplots(1, 3, figsize=(11.6, 3.5))
# (a) vertex_gap
ax = axs[0]; frame(ax, (-0.1, 2.6), (-0.95, 0.95), u'(a) vertex_gap — hai tường cắt nhau ở XA')
ax.plot([1.2, 2.4], [0.8, -0.4], color=MUT, lw=2.4)
ax.plot([1.2, 2.4], [-0.8, 0.4], color=MUT, lw=2.4)
ax.plot([1.8], [0.2], marker='x', ms=9, color=WARN, mew=2, zorder=7)
ax.plot([1.8], [0.2], marker='o', ms=26, mfc='none', mec=WARN, lw=1.0, ls=':', zorder=6)
ax.annotate(u'giao điểm có,\nnhưng KHÔNG đầu đoạn nào\nkết thúc tại đó → LOẠI',
(1.8, 0.2), textcoords='offset points', xytext=(-4, 30), fontsize=7.5,
color=WARN, ha='center')
ax.annotate(u'Mọi cặp đường không song song\nđều có giao điểm. Chỉ chữ V thật\nmới có hai đoạn KẾT THÚC ở đó.',
(0.05, -0.88), fontsize=7.5, color=INK)
# (b) angle_tolerance
ax = axs[1]; frame(ax, (-0.1, 2.6), (-0.95, 0.95), u'(b) angle_tolerance — đúng đỉnh, sai góc')
v_plate(ax, apex=2.0, vang=math.pi / 2, wl=0.32, color='#b9c2cc', lw=2.0)
v_plate(ax, apex=2.0, vang=2.6, wl=0.32, color=WARN, lw=2.6)
ax.annotate(u'profile: 90°', (1.62, 0.30), fontsize=7.5, color='#7d8996')
ax.annotate(u'đo được: 149°\n→ LOẠI', (1.55, -0.44), fontsize=7.5, color=WARN)
ax.annotate(u'Góc đo giữa hai VECTOR CÁNH\nxuất phát từ đỉnh — không phải\ngiữa hai pháp tuyến.',
(0.05, -0.88), fontsize=7.5, color=INK)
# (c) luat chieu dai bat doi xung
ax = axs[2]; frame(ax, (-0.1, 2.6), (-0.95, 0.95), u'(c) chiều dài — luật BẤT ĐỐI XỨNG')
apex = 2.0
ax.plot([apex, apex - 0.212], [0, 0.212], color=INK, lw=2.6)
ax.plot([apex, apex - 0.212], [0, -0.212], color='#b9c2cc', lw=2.6, ls=(0, (4, 3)))
ax.plot([apex, apex - 0.10], [0, -0.10], color=WARN, lw=2.6)
for b in (0.03, 0.09, 0.15, 0.21, 0.27):
ax.plot([0, apex * 1.12], [0, b * 3.4], color='#e9edf1', lw=0.7, zorder=1)
ax.annotate(u'cánh gần: đủ 0.30 m', (apex - 0.30, 0.27), fontsize=7.5, color=INK)
ax.annotate(u'cánh xa: chỉ thấy 0.14 m\n(gần song song với tia)', (apex - 0.62, -0.42),
fontsize=7.5, color=WARN)
ax.annotate(u'Che khuất chỉ làm cánh NGẮN đi.\nLuật: không cánh nào DÀI hơn ngưỡng,\nít nhất MỘT cánh đúng ngưỡng.',
(0.05, -0.88), fontsize=7.5, color=INK)
save(fig, 'v_gates.svg')
def fig_v_tape():
fig, axs = plt.subplots(1, 2, figsize=(11.6, 4.0),
gridspec_kw={'width_ratios': [1.15, 1]})
# trai: hinh hoc dai
ax = axs[0]; frame(ax, (1.55, 2.35), (-0.36, 0.36), u'Dải phản quang trên tấm chữ V')
t1, t2 = v_plate(ax)
# dai o giua canh, dai tape_w doc canh
TW = 0.12
cs = []
for sy in (1, -1):
dx, dy = (TIPX - AP) / WL, sy * TIPY / WL
mx, my = AP + dx * WL / 2, dy * WL / 2
ax.plot([mx - dx * TW / 2, mx + dx * TW / 2], [my - dy * TW / 2, my + dy * TW / 2],
color='#e8b923', lw=6.0, solid_capstyle='butt', zorder=5)
cs.append((mx, my))
ax.plot([c[0] for c in cs], [c[1] for c in cs], color=WARN, lw=1.0, ls=':', zorder=6)
dim(ax, cs[0], cs[1], u'tape_spacing = 0.1945 m', off=0.0)
dxa, dya = (TIPX - AP) / WL, TIPY / WL
dim(ax, (cs[0][0] - dxa * TW / 2, cs[0][1] - dya * TW / 2),
(cs[0][0] + dxa * TW / 2, cs[0][1] + dya * TW / 2),
u'tape_width = 0.12 m', off=0.055, color='#8a6d00')
ax.annotate(u'khoảng cách đo THẲNG giữa hai TÂM dải,\nkhông đi vòng theo cánh, không qua đỉnh',
(1.58, -0.31), fontsize=7.5, color=WARN)
# phai: bu luong tu hoa
ax = axs[1]; frame(ax, (-0.02, 0.20), (-0.062, 0.075),
u'Vì sao chiều dài dải luôn bị ĐO HỤT')
ax.plot([0.0, 0.16], [0, 0], color='#e8b923', lw=9, solid_capstyle='butt', zorder=3)
ax.annotate(u'dải THẬT, 0.12 m quy đổi', (0.055, 0.016), fontsize=7.5, color='#8a6d00')
step = 0.16 / 6.0
hits = [0.0 + step * (i + 0.5) for i in range(6)]
for h in hits:
ax.plot([h], [0], marker='o', ms=6, color=ACC, zorder=6)
dim(ax, (hits[0], 0), (hits[-1], 0), u'đo được = (n−1) bước', off=-0.030,
color=ACC, above=False)
dim(ax, (0.0, 0), (0.16, 0), u'thật = n bước', off=0.036, color=WARN)
ax.annotate(u'Tia sáng ngoài cùng nằm BÊN TRONG dải,\nkhông đúng ở mép — thiếu tới một bước tia.\n'
u'Ở 3 m một bước nanoscan3 là 0.021 m,\ntức 17% của dải 0.12 m: LỆCH HỆ THỐNG.\n\n'
u'Bù: n tia trải đúng n−1 bước, nên cộng\nthêm MỘT bước = thêm nửa bước mỗi mép.\n'
u'Bước tia lấy từ chính vệt đó → tự hiệu\nchỉnh theo tầm và độ chếch, không thêm\ntham số nào.',
(-0.01, -0.058), fontsize=7.3, color=INK)
save(fig, 'v_tape.svg')
def fig_v_offset():
fig, ax = plt.subplots(figsize=(8.6, 3.6))
frame(ax, (-0.05, 2.55), (-0.78, 0.78), u'offset_x cho chữ V — vì sao KHÔNG ai cộng footprint hộ')
v_plate(ax)
ax.plot([AP], [0], marker='o', ms=6, color=WARN, zorder=7)
gx = AP - 0.95
# robot
ax.add_patch(Rectangle((gx - 0.583, -0.48), 1.166, 0.96, fc='#eef3f8', ec=ACC,
lw=1.6, zorder=3))
ax.plot([gx], [0], marker='*', ms=15, color='#7b3fbf', zorder=8)
ax.annotate(u'base_link', (gx, 0), textcoords='offset points', xytext=(0, -13),
fontsize=7.5, color='#7b3fbf', ha='center')
segs = [(gx, gx + 0.583, u'rear_extent\n0.583'),
(gx + 0.583, gx + 0.653, u'padding\n0.070'),
(gx + 0.653, gx + 0.865, u'đầu cánh nhô\n0.212'),
(gx + 0.865, AP, u'khe hở\n0.080')]
for i, (a, b, lab) in enumerate(segs):
yy = 0.56 + 0.0
ax.plot([a, a], [0, yy], color=MUT, lw=0.6, ls=':', zorder=2)
ax.plot([b, b], [0, yy], color=MUT, lw=0.6, ls=':', zorder=2)
dim(ax, (a, yy), (b, yy), lab, off=0.0, color=WARN, fs=7)
dim(ax, (gx, 0), (AP, 0), u'offset_x = 0.583 + 0.070 + 0.212 + 0.080 = 0.945 → 0.95 m',
off=-0.66, color='#7b3fbf', above=False)
save(fig, 'v_offset.svg')
# =================================================================================================
# CUNG TRON LOM
# =================================================================================================
CX, R, SPAN = 1.60, 0.40, 2.0 # tâm ở 1.60 m, bán kính 0.40, mở 2.0 rad
DEEP = CX + R # điểm sâu nhất ở 2.00 m
def cradle(ax, cx=CX, r=R, span=SPAN, color=INK, lw=2.8, z=4, concave=True):
t = [(-span / 2 + span * i / 240.0) for i in range(241)]
if concave:
xs = [cx + r * math.cos(a) for a in t]
else:
xs = [cx - r * math.cos(a) for a in t]
ys = [r * math.sin(a) for a in t]
ax.plot(xs, ys, color=color, lw=lw, zorder=z, solid_capstyle='round')
return (xs[0], ys[0]), (xs[-1], ys[-1])
def fig_arc_geometry():
fig, ax = plt.subplots(figsize=(7.8, 4.6))
frame(ax, (-0.15, 2.45), (-0.85, 0.85))
sensor(ax)
e1, e2 = cradle(ax)
ax.plot([CX], [0], marker='o', ms=6, color=ACC, zorder=7)
ax.annotate(u'tâm C — nằm PHÍA CẢM BIẾN\n(đây là điều làm nó LÕM)', (CX, 0),
textcoords='offset points', xytext=(-118, 18), fontsize=8, color=ACC)
for e in (e1, e2):
ax.plot([CX, e[0]], [0, e[1]], color=MUT, lw=0.9, ls=':', zorder=3)
dim(ax, (CX, 0), e1, u'arc_radius = 0.40 m', off=0.0, color=WARN)
a1 = math.degrees(math.atan2(e2[1], e2[0] - CX))
a2 = math.degrees(math.atan2(e1[1], e1[0] - CX))
ax.add_patch(Arc((CX, 0), 0.34, 0.34, theta1=a1, theta2=a2, color=ACC, lw=1.4, zorder=6))
ax.annotate(u'arc_span — góc mở đo TẠI TÂM\n2.0 rad = 114.6°', (CX + 0.18, 0),
textcoords='offset points', xytext=(6, -34), fontsize=8, color=ACC)
ax.plot([DEEP], [0], marker='o', ms=7, color=WARN, zorder=8)
ax.annotate(u'điểm SÂU NHẤT\nP = C · (1 + R/|C|)', (DEEP, 0),
textcoords='offset points', xytext=(8, 26), fontsize=8, color=WARN)
arrow(ax, (DEEP, 0), (DEEP - 0.55, 0), color='#0d8050', lw=1.8)
ax.annotate(u'yaw — hướng từ P về phía cảm biến', (DEEP - 0.56, 0),
textcoords='offset points', xytext=(-8, 12), fontsize=8,
color='#0d8050', ha='right')
gx = DEEP - 0.92
ax.plot([gx], [0], marker='*', ms=15, color='#7b3fbf', zorder=8)
dim(ax, (DEEP, 0), (gx, 0), u'offset_x = 0.92 m', off=-0.34, color='#7b3fbf', above=False)
ax.annotate(u'P chỉ phụ thuộc TÂM và BÁN KÍNH — cả hai từ phép khớp —\n'
u'nên nó KHÔNG dịch khi một phần cung bị che.\n'
u'Lấy trung điểm cung nhìn thấy thì dễ hơn, nhưng lệch ngay khi khuất một bên.',
(-0.12, -0.80), fontsize=7.5, color=INK)
save(fig, 'arc_geometry.svg')
def fig_arc_concave_convex():
fig, axs = plt.subplots(1, 2, figsize=(10.4, 3.9))
for ax, concave in zip(axs, (True, False)):
ttl = (u'LÕM (pattern: arc) — máng ôm robot' if concave
else u'LỒI (cylinder) — trụ tròn, CHƯA hiện thực')
frame(ax, (-0.1, 2.6), (-0.75, 0.75), ttl)
sensor(ax, label=u'cảm biến')
cradle(ax, concave=concave)
ax.plot([CX], [0], marker='o', ms=6, color=ACC, zorder=7)
ax.annotate(u'C', (CX, 0), textcoords='offset points', xytext=(-4, 7),
fontsize=9, color=ACC, ha='center')
# cu ly trung binh cua diem mat so voi |C|
mean_r = CX + (R * 0.6 if concave else -R * 0.6)
ax.plot([0, CX], [0, 0], color=ACC, lw=0.9, ls=':', zorder=3)
if concave:
ax.plot([DEEP], [0], marker='o', ms=7, color=WARN, zorder=8)
ax.annotate(u'|C| < cự ly TB các điểm mặt\n→ tâm nằm GIỮA cảm biến và mặt cong',
(0.02, -0.66), fontsize=7.5, color='#0d8050')
ax.annotate(u'P đúng chỗ', (DEEP, 0), textcoords='offset points',
xytext=(8, 10), fontsize=7.5, color=WARN)
else:
ax.plot([CX + R], [0], marker='x', ms=11, color=WARN, mew=2.2, zorder=8)
ax.annotate(u'|C| > cự ly TB các điểm mặt\n→ tâm nằm SAU mặt cong: LOẠI',
(0.02, -0.66), fontsize=7.5, color=WARN)
ax.annotate(u'nếu nhận nhầm, P rơi vào ĐÂY —\nbên trong vật. Robot được lệnh\nlái xuyên qua nó.',
(CX + R, 0), textcoords='offset points', xytext=(-30, 16),
fontsize=7.5, color=WARN, ha='right')
save(fig, 'arc_concave.svg')
fig_arc_geometry(); fig_arc_concave_convex()

View File

@@ -38,6 +38,19 @@ struct CircleFitResult
/// [rad] Góc mở của cung ĐO ĐƯỢC, từ điểm đầu tới điểm cuối nhìn từ tâm. /// [rad] Góc mở của cung ĐO ĐƯỢC, từ điểm đầu tới điểm cuối nhìn từ tâm.
double span = 0.0; double span = 0.0;
/**
* [rad] Hướng từ TÂM tới TRUNG ĐIỂM cung, tức phân giác của hai bán kính tới hai đầu mút.
*
* Đây là đại lượng duy nhất trong kết quả này nói lên **trục của chính vật**, không phụ thuộc
* chỗ người quan sát đứng. Một đường tròn không có trục nào cả; chỉ cung vật lý mới có, và trục
* đó nằm ở đây.
*
* @warning Chỉ đúng khi thấy được CẢ HAI đầu mút thật của cung. Che mất một bên thì trung điểm
* quan sát được dịch theo, và trục dịch theo đúng ngần ấy. Người gọi phải so @ref span
* với góc mở toàn phần của vật để biết có tin được hay không.
*/
double mid_angle = 0.0;
std::size_t point_count = 0; std::size_t point_count = 0;
}; };

View File

@@ -89,16 +89,33 @@ struct DockProfile
double arc_radius_tolerance = 0.06; double arc_radius_tolerance = 0.06;
/** /**
* [rad] Góc mở TOÀN PHẦN của máng — bao nhiêu cung thật sự tồn tại trên tấm. * [rad] Góc mở TOÀN PHẦN của máng — bao nhiêu cung THẬT SỰ tồn tại trên tấm.
* *
* Đây là cận TRÊN, không phải giá trị phải khớp đúng. Lý do giống hệt luật chiều dài cánh chữ V: * Kiểm HAI PHÍA, khác hẳn luật chiều dài cánh chữ V. Lý do: với chữ V, đỉnh và phân giác là thuộc
* che khuất và nhìn chếch chỉ làm cung NGẮN đi, không bao giờ dài ra. Bắt khớp đúng nghĩa là chỉ * tính nội tại, nhìn thấy một cánh ngắn vẫn suy ra đúng. Với cung tròn thì KHÔNG — trục của máng
* dò được khi nhìn trọn cả máng. * chỉ suy được từ hai đầu mút, nên thấy thiếu cung là trục sai, và sai một cách âm thầm.
* *
* Cung quan sát được dài HƠN ngần này thì không phải cái máng đó — là một mặt cong khác. * Quan hệ đo được: sai yaw ≈ (arc_span − góc mở đo được) / 2.
* Nên `arc_span_tolerance` chính là ngân sách sai hướng, nhân đôi.
*
* ► Đặt bằng góc mở THẬT của máng, KHÔNG cộng dư. Cộng dư là tự nới cổng theo chiều nguy hiểm.
*/ */
double arc_span = 2.0; double arc_span = 2.0;
/**
* [rad] Sai lệch góc mở còn chấp nhận, tính cả hai chiều.
*
* Thiếu cung -> trục lệch (xem `arc_span`). Thừa cung -> đang nhìn một mặt cong khác, không phải
* cái máng.
*
* Bộ trích đoạn luôn cắt bớt vài tia ở hai mép, nên ngay cả khi nhìn chính diện, góc mở đo được
* vẫn hụt khoảng 0.04 rad so với thật. Dung sai phải phủ được phần đó cộng phần che khuất mà ta
* chấp nhận.
*
* Mặc định 0.15 rad: cho phép nhìn chếch tới khoảng 30 độ, đổi lại sai hướng tối đa ~2.4 độ.
*/
double arc_span_tolerance = 0.15;
/** /**
* [rad] Góc mở tối thiểu quan sát được thì mới tin phép khớp. * [rad] Góc mở tối thiểu quan sát được thì mới tin phép khớp.
* *

View File

@@ -187,14 +187,17 @@ Detection ArcPatternMatcher::match(const std::vector<Line>& lines) const
continue; continue;
} }
// Góc mở quan sát được: sàn là cổng SỐ HỌC (dưới đó bán kính khớp bắt đầu lệch nhanh), trần là // Sàn số học: dưới ngưỡng này bán kính khớp bắt đầu lệch nhanh, bất kể máng to nhỏ.
// cổng HÌNH HỌC (cung dài hơn cả cái máng thì là mặt cong khác).
if (fit.span < profile_.arc_min_span) if (fit.span < profile_.arc_min_span)
{ {
++rejected_span; ++rejected_span;
continue; continue;
} }
if (fit.span > profile_.arc_span + profile_.arc_radius_tolerance / std::max(fit.radius, 1e-6))
// Cổng góc mở, HAI PHÍA. Thừa cung = đang nhìn mặt cong khác. Thiếu cung = mép bị che, và khi
// ấy trung điểm cung dịch đi — mà trục của máng lấy từ chính trung điểm đó. Đo được: góc mở
// hụt δ thì hướng sai khoảng δ/2, nên bỏ cổng dưới là để trục sai đi qua trong im lặng.
if (std::fabs(fit.span - profile_.arc_span) > profile_.arc_span_tolerance)
{ {
++rejected_span; ++rejected_span;
continue; continue;
@@ -224,14 +227,22 @@ Detection ArcPatternMatcher::match(const std::vector<Line>& lines) const
continue; continue;
} }
// Điểm sâu nhất: trên đường tròn, dọc hướng cảm biến -> tâm, ra xa thêm một bán kính. Chỉ phụ // Trục của MÁNG, lấy từ trung điểm cung — phân giác hai bán kính tới hai đầu mút.
// thuộc tâm và bán kính nên không đổi khi một phần cung bị che. //
const double scale = 1.0 + fit.radius / center_range; // Trước đây chỗ này lấy điểm trên đường tròn XA CẢM BIẾN NHẤT, và hướng từ đó về phía cảm biến.
const double apex_x = fit.center_x * scale; // Cả hai định nghĩa theo VỊ TRÍ NGƯỜI QUAN SÁT, nên bộ dò luôn báo rằng cái máng quay mặt đúng
const double apex_y = fit.center_y * scale; // vào chỗ robot đang đứng. Đo được: đứng lệch 10/20/30/40 độ thì yaw sai đúng 10/20/30/40 độ,
// và điểm đích trượt dọc cung theo. Nó ổn định thật — nhưng ổn định ở GIÁ TRỊ SAI.
//
// Một ĐƯỜNG TRÒN không có trục nào cả. Chỉ CUNG vật lý mới có, và trục đó là phân giác hai đầu
// mút. Đổi lại: che mất một bên thì trung điểm dịch theo, nên cổng `arc_span` phải kiểm HAI
// PHÍA — thấy thiếu cung cũng nguy hiểm ngang thấy thừa.
const double apex_x = fit.center_x + fit.radius * std::cos(fit.mid_angle);
const double apex_y = fit.center_y + fit.radius * std::sin(fit.mid_angle);
// Hướng từ điểm sâu nhất về phía cảm biến, cùng quy ước với chữ V. // Hướng RA phía miệng máng: ngược với hướng tâm -> mặt cong. Cùng quy ước với chữ V.
const double yaw = std::atan2(-fit.center_y, -fit.center_x); const double yaw =
std::atan2(std::sin(fit.mid_angle + M_PI), std::cos(fit.mid_angle + M_PI));
if (profile_.has_prior) if (profile_.has_prior)
{ {
@@ -298,10 +309,11 @@ Detection ArcPatternMatcher::match(const std::vector<Line>& lines) const
if (have_near) if (have_near)
{ {
std::snprintf(detail, sizeof(detail), std::snprintf(detail, sizeof(detail),
" (nearest fit: radius %.3f m vs %.3f+-%.3f, span %.3f rad (min %.3f, max" " (nearest fit: radius %.3f m vs %.3f+-%.3f, span %.3f rad vs %.3f+-%.3f"
" %.3f), rms %.4f m vs max %.4f)", " (floor %.3f), rms %.4f m vs max %.4f)",
near_radius, profile_.arc_radius, profile_.arc_radius_tolerance, near_span, near_radius, profile_.arc_radius, profile_.arc_radius_tolerance, near_span,
profile_.arc_min_span, profile_.arc_span, near_rms, profile_.arc_max_rms); profile_.arc_span, profile_.arc_span_tolerance, profile_.arc_min_span,
near_rms, profile_.arc_max_rms);
} }
if (rejected_prior > 0) if (rejected_prior > 0)
@@ -330,7 +342,8 @@ Detection ArcPatternMatcher::match(const std::vector<Line>& lines) const
else if (rejected_span > 0) else if (rejected_span > 0)
{ {
best.reason = std::to_string(rejected_span) + best.reason = std::to_string(rejected_span) +
" arc(s) fitted cleanly but span too little or too much of a circle"; " arc(s) fitted cleanly but span the wrong amount of circle — too little means"
" an edge is hidden and the axis would be wrong, too much means another surface";
best.reason += detail; best.reason += detail;
} }
else if (rejected_rms > 0) else if (rejected_rms > 0)

View File

@@ -188,6 +188,19 @@ CircleFitResult fitCircle(const std::vector<double>& xs, const std::vector<doubl
out.rms_error = std::sqrt(sq_sum / static_cast<double>(n)); out.rms_error = std::sqrt(sq_sum / static_cast<double>(n));
out.span = angle_max - angle_min; out.span = angle_max - angle_min;
// Trung điểm cung, quy về (-pi, pi]. `angle_min`/`angle_max` nằm trong hệ đã cộng dồn neo tại
// góc thật của điểm đầu, nên trung điểm của chúng cũng là một góc thật, chỉ lệch bội của 2*pi.
double mid = 0.5 * (angle_min + angle_max);
while (mid > M_PI)
{
mid -= 2.0 * M_PI;
}
while (mid <= -M_PI)
{
mid += 2.0 * M_PI;
}
out.mid_angle = mid;
out.valid = true; out.valid = true;
return out; return out;
} }

View File

@@ -142,6 +142,13 @@ bool DockProfile::validate(std::string& error) const
error = "arc_span must be finite, > 0 and <= 2*pi rad"; error = "arc_span must be finite, > 0 and <= 2*pi rad";
return false; return false;
} }
if (!positive(arc_span_tolerance) || arc_span_tolerance >= arc_span)
{
// Dung sai >= chính góc mở nghĩa là chấp nhận cả cung dài 0 — cổng vô nghĩa, mà cổng này là
// thứ duy nhất chặn trục sai.
error = "arc_span_tolerance must be finite, > 0 and < arc_span";
return false;
}
if (!positive(arc_min_span) || arc_min_span > arc_span) if (!positive(arc_min_span) || arc_min_span > arc_span)
{ {
// Sàn cao hơn cả góc mở toàn phần thì không cung nào lọt được, kể cả cái máng thật. // Sàn cao hơn cả góc mở toàn phần thì không cung nào lọt được, kể cả cái máng thật.

View File

@@ -116,8 +116,9 @@ DockProfile arcProfile()
p.pattern = PatternType::kArc; p.pattern = PatternType::kArc;
p.arc_radius = 0.40; // [m] p.arc_radius = 0.40; // [m]
p.arc_radius_tolerance = 0.06; // [m] p.arc_radius_tolerance = 0.06; // [m]
p.arc_span = 2.2; // [rad] toàn phần của máng p.arc_span = 2.0; // [rad] góc mở THẬT của máng, không cộng dư
p.arc_min_span = 0.52; // [rad] p.arc_span_tolerance = 0.20; // [rad] hai phía
p.arc_min_span = 0.52; // [rad] sàn số học
p.arc_max_rms = 0.010; // [m] p.arc_max_rms = 0.010; // [m]
p.min_arc_points = 8; p.min_arc_points = 8;
p.min_confidence = 0.3; p.min_confidence = 0.3;
@@ -207,50 +208,63 @@ TEST(ArcPatternMatcher, TheOffsetMovesTheTargetOutTowardsTheRobot)
EXPECT_NEAR(d.y, 0.00, 0.03); EXPECT_NEAR(d.y, 0.00, 0.03);
} }
TEST(ArcPatternMatcher, APartlyOccludedArcStillGivesTheSameDeepestPoint) TEST(ArcPatternMatcher, ThePoseFollowsTheDockNotTheRobot)
{ {
// Đây là lý do điểm đích được định nghĩa từ TÂM và BÁN KÍNH chứ không phải trung điểm cung quan // ĐÂY LÀ TEST QUAN TRỌNG NHẤT CỦA CẢ TỆP.
// sát được: che một bên thì trung điểm dịch ngay, còn tâm thì không. //
// Bản đầu lấy điểm trên đường tròn XA CẢM BIẾN NHẤT làm đích, và hướng từ đó về phía cảm biến làm
// yaw. Cả hai định nghĩa theo VỊ TRÍ NGƯỜI QUAN SÁT, nên bộ dò luôn báo rằng cái máng quay mặt
// đúng vào chỗ robot đang đứng — và không dòng log nào tỏ ra bất thường.
//
// Cách kiểm PHẢI là xoay CÁI MÁNG, không phải xoay cả thế giới quanh cảm biến: xoay cả thế giới
// thì quan hệ cảm biến↔máng không đổi, và định nghĩa cũ vẫn ra đúng. Đó là một test vô dụng, và
// bản nháp của test này chính là như vậy.
//
// Ở đây tâm máng đứng NGUYÊN một chỗ; chỉ hướng của máng đổi. Định nghĩa cũ cho ra cùng một yaw
// trong cả hai lượt vì tâm không đổi. Định nghĩa đúng phải đi theo hướng của máng.
Rig rig; Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_; ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection full = rig.run(concaveCradle(1.60, 0.40, 2.0)); const double cx = 1.60;
ASSERT_TRUE(full.valid) << full.reason; const double r = 0.40;
const double span = 2.0;
// Chỉ còn nửa bên phải của cung. for (const double axis : { 0.0, 0.35 }) // [rad] huong cua mang, 0.35 rad = 20 do
const Detection half = rig.run(arcSegments(1.60, 0.0, 0.40, 0.0, 1.0)); {
ASSERT_TRUE(half.valid) << half.reason; // Cung vẽ đối xứng quanh `axis` tính từ TÂM; mặt cong ở xa hơn tâm nên vẫn là máng lõm.
const Detection d = rig.run(arcSegments(cx, 0.0, r, axis - span / 2.0, span));
ASSERT_TRUE(d.valid) << "axis=" << axis << ": " << d.reason;
EXPECT_NEAR(half.apex_x, full.apex_x, 0.03); // Đích = tâm + bán kính theo hướng máng. Hướng ra miệng = axis + pi.
EXPECT_NEAR(half.apex_y, full.apex_y, 0.03); const double want_x = cx + r * std::cos(axis);
const double want_y = r * std::sin(axis);
const double want_yaw = std::atan2(std::sin(axis + M_PI), std::cos(axis + M_PI));
double dyaw = std::atan2(std::sin(d.yaw - want_yaw), std::cos(d.yaw - want_yaw));
EXPECT_NEAR(d.apex_x, want_x, 0.03) << "axis=" << axis;
EXPECT_NEAR(d.apex_y, want_y, 0.03) << "axis=" << axis;
EXPECT_LT(std::fabs(dyaw), 0.09)
<< "axis=" << axis << ": yaw lech " << dyaw * 180.0 / M_PI
<< " do — pose dang bam theo cho robot dung, khong theo huong mang";
}
} }
TEST(ArcPatternMatcher, AWallJustPastTheArcIsNotAbsorbedIntoIt) TEST(ArcPatternMatcher, RefusesAnArcWithAnEdgeHiddenBecauseTheAxisWouldBeWrong)
{ {
// Hồi quy cho một lỗi CHỈ SIM MỚI LỘ. Ban đầu phép gom chỉ xét khoảng cách theo SỐ TIA, và trong // Mặt kia của test trên. Trục của máng suy từ HAI đầu mút; che mất một bên là trung điểm cung
// world Gazebo bức tường ngay sau máng chỉ cách 2 tia — lọt ngưỡng. Bốn đoạn của máng bị gom // dịch đi, và trục dịch theo đúng ngần ấy — âm thầm, không có dấu hiệu nào khác.
// cùng bức tường 6.6 m, khớp tròn trên cả cụm cho bán kính 3.2 m và sai số 0.11 m, nên cái máng
// thật bị loại vì một thứ không thuộc về nó.
// //
// Liền nhau theo số tia KHÔNG có nghĩa là liền nhau trong không gian: tia kế tiếp có thể rơi // Bản trước có một test khẳng định ngược lại: cung bị che nửa vẫn ra "cùng điểm sâu nhất". Đúng
// xuống một mặt cách đó vài mét. // theo định nghĩa cũ, và chính vì thế định nghĩa cũ sai — nó ổn định bằng cách không nhìn vào
// hình dạng vật.
//
// Không suy được trục thì phải TỪ CHỐI, không được đoán.
Rig rig; Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_; ASSERT_TRUE(rig.ok_) << rig.error_;
// Máng ở 2 m; mép của nó nằm quanh bearing +-0.17 rad. const Detection d = rig.run(arcSegments(1.60, 0.0, 0.40, 0.0, 1.0)); // chi con nua ben phai
std::vector<Segment> world = concaveCradle(1.60, 0.40, 2.0); EXPECT_FALSE(d.valid) << d.reason;
EXPECT_NE(d.reason.find("edge is hidden"), std::string::npos) << d.reason;
// Tường ở 4 m, bắt đầu ngay sát mép máng theo GÓC nhưng cách xa theo KHÔNG GIAN.
const double a0 = 0.18;
const double a1 = 0.95;
world.push_back({ 4.0 * std::cos(a0), 4.0 * std::sin(a0), 4.0 * std::cos(a1),
4.0 * std::sin(a1) });
const Detection d = rig.run(world);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.apex_x, 2.00, 0.03);
EXPECT_NEAR(d.measured_arc_radius, 0.40, 0.03);
EXPECT_LT(d.measured_arc_rms, 0.010) << "sai so khop no ra = da nuot ca buc tuong";
} }
// ================================================================================================ // ================================================================================================
@@ -312,7 +326,8 @@ TEST(ArcPatternMatcher, RefusesAnArcThatShowsTooLittleOfItself)
TEST(ArcPatternMatcher, RefusesAnArcThatSpansMoreThanTheProfileSays) TEST(ArcPatternMatcher, RefusesAnArcThatSpansMoreThanTheProfileSays)
{ {
DockProfile p = arcProfile(); DockProfile p = arcProfile();
p.arc_span = 1.0; // [rad] mang that chi mo 1.0 rad p.arc_span = 1.0; // [rad] máng thật chỉ mở 1.0 rad
p.arc_span_tolerance = 0.20; // [rad]
Rig rig(p); Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_; ASSERT_TRUE(rig.ok_) << rig.error_;
@@ -363,6 +378,11 @@ TEST(ArcPatternMatcher, RefusesAProfileThatCanNeverMatch)
EXPECT_FALSE(m.configure(p, error)); EXPECT_FALSE(m.configure(p, error));
EXPECT_NE(error.find("arc_radius_tolerance"), std::string::npos) << error; EXPECT_NE(error.find("arc_radius_tolerance"), std::string::npos) << error;
p = arcProfile();
p.arc_span_tolerance = p.arc_span; // dung sai nuot tron phep do
EXPECT_FALSE(m.configure(p, error));
EXPECT_NE(error.find("arc_span_tolerance"), std::string::npos) << error;
p = arcProfile(); p = arcProfile();
p.arc_min_span = p.arc_span + 0.1; // san cao hon tran: khong cung nao lot p.arc_min_span = p.arc_span + 0.1; // san cao hon tran: khong cung nao lot
EXPECT_FALSE(m.configure(p, error)); EXPECT_FALSE(m.configure(p, error));