harryzhang1018's picture
Add reproduction code and README
0c3dd1d verified
Raw History Blame Contribute Delete
7.49 kB
"""MPC failures in the S2 recovery tests (B01): start pose vs the region where the MPC cost has a second minimum.
Classifies the 400 B01 MPC starts (div = divergence, noentry = no tube entry without divergence, ok = reached the
tube) and counts the starts beyond the e_long = 0 boundary (reference point beside/behind the car, 1 m lookahead) and
beyond the ridge of the released MPC stage cost 5500 e_lat^2 + 3500 e_head^2. Start offset and heading are taken
from the controller's first tick (first_tick.py). Closed-form geometry; no new simulation.
Usage: python d3_range.py <per_start_dir> <b01_mpc_first_tick.csv> <out_json> <fig_png>
"""
import csv, gzip, glob, json, os, sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
PER_START, TICKS, OUT, FIG = sys.argv[1:5]
INK, MUTED, GRID, BLUE, ORANGE, GRAY = '#1f2328', '#5b6470', '#e6e8eb', '#2a78d6', '#eb6834', '#b4bac2'
rows = []
for f in sorted(glob.glob(os.path.join(PER_START, 'B01_main_tr/recovery_part*.csv.gz'))):
rows += [r for r in csv.DictReader(gzip.open(f, 'rt')) if r['ctrl_label'] == 'mpc']
first_tick = {r['scenario_id']: r for r in csv.DictReader(open(TICKS))}
pts = []
for r in rows:
sid = r['scenario_id']
t = first_tick[sid]
et = [float(t[f'et{i}']) for i in range(3)]
psi = -et[2]; y = -(np.sin(psi) * et[0] + np.cos(psi) * et[1])
toward = -np.sign(y) * psi # heading angle toward the path (rad), < 0 = away
d = abs(y)
div = r['div_flag'] in ('1', 'True', 'true')
cls = 'div' if div else ('noentry' if r['reason25_trk100_L010H010_first'] != 'success' else 'ok')
pts.append({'sid': sid, 'd': d, 'toward_deg': float(np.degrees(toward)), 'e_long0_logged': float(t['e0']),
'e_long0_closed': float(np.cos(toward) ** 2 + d * np.sin(toward)), 'cls': cls})
def a_elong0(d): # away angle where the reference point is beside the car (e_long = 0), lookahead 1 m
return np.degrees(np.arcsin((-d + np.sqrt(d * d + 4)) / 2))
def a_ridge_elat(d): # away angle where d(e_lat)/d(heading) = 0 for the true lookahead-reselected error
return np.degrees(np.arcsin((-d + np.sqrt(d * d + 8)) / 4))
def stage_cost(d, toward_rad): # released stage cost 5500 e_lat^2 + 3500 e_head^2, car d below the path
psi = toward_rad
return 5500 * (np.cos(psi) * (d - np.sin(psi))) ** 2 + 3500 * psi ** 2
_AW = np.radians(np.linspace(0, 89.9, 8991))
def a_ridge(d): # away angle of the local maximum of the released stage cost (the cost ridge)
d = np.atleast_1d(d)
out = np.array([np.degrees(_AW[np.argmax(stage_cost(x, -_AW))]) for x in d])
return out if out.size > 1 else float(out[0])
for p in pts:
a = -p['toward_deg']
p['beyond_elong0'] = a > a_elong0(p['d']); p['beyond_ridge'] = a > a_ridge(p['d'])
summ = {}
for k in ('div', 'noentry', 'ok'):
g = [p for p in pts if p['cls'] == k]
summ[k] = {'n': len(g), 'beyond_elong0': sum(p['beyond_elong0'] for p in g), 'beyond_ridge': sum(p['beyond_ridge'] for p in g)}
summ['all'] = {'n': len(pts), 'beyond_elong0': sum(p['beyond_elong0'] for p in pts), 'beyond_ridge': sum(p['beyond_ridge'] for p in pts)}
beyond = [p for p in pts if p['beyond_elong0']]
summ['divergence_rate_beyond_elong0'] = sum(p['cls'] == 'div' for p in beyond) / max(len(beyond), 1)
summ['divergence_rate_inside'] = sum(p['cls'] == 'div' for p in pts if not p['beyond_elong0']) / max(len(pts) - len(beyond), 1)
summ['boundaries_deg_away'] = {f'{d:.1f}': {'e_long0': float(a_elong0(d)), 'stage_cost_ridge': float(a_ridge(d)), 'e_lat_ridge': float(a_ridge_elat(d))} for d in (1.5, 2.0, 2.5)}
summ['max_abs_closed_vs_logged_e_long0'] = max(abs(p['e_long0_logged'] - p['e_long0_closed']) for p in pts)
json.dump({'label': 'B01 MPC starts (Chrono digital twin) and closed-form geometry; no new simulation', 'summary': summ, 'points': pts},
open(OUT, 'w'), indent=1, default=float)
print(json.dumps(summ, indent=1, default=float))
# ---------------- figure ----------------
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 11, 'axes.edgecolor': MUTED, 'axes.labelcolor': INK,
'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.spines.top': False, 'axes.spines.right': False})
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.6), gridspec_kw={'wspace': 0.28})
# (a) released stage cost vs heading, car 2.0 m from the path
dd = 2.0
h = np.radians(np.linspace(-90, 90, 721)) # heading toward the path
y = -dd; psi = h # car below the path, psi > 0 points toward it
e2 = -np.cos(psi) * (y + np.sin(psi)); e3 = -psi
J = 5500 * e2 ** 2 + 3500 * e3 ** 2
ax1.axvspan(-45, 45, color=GRID, zorder=0)
ax1.text(0, 0.6, 'paper start range (±45°)', ha='center', va='bottom', color=MUTED, fontsize=10)
ax1.plot(np.degrees(h), J / 1000, color=BLUE, lw=2)
i_r = np.argmax(np.where(np.degrees(h) < 0, J, -1)); i_a = np.argmin(np.where(np.degrees(h) < -30, J, 1e12))
i_t = np.argmin(np.where(np.degrees(h) > 0, J, 1e12))
for i, txt, dy, ha in ((i_r, f'ridge {np.degrees(h[i_r]):.0f}°', 0.9, 'left'),
(i_a, f'"away" minimum {np.degrees(h[i_a]):.0f}°', 1.5, 'left'),
(i_t, f'"toward" minimum +{np.degrees(h[i_t]):.0f}°', 1.5, 'center')):
ax1.plot(np.degrees(h[i]), J[i] / 1000, 'o', ms=8, color=BLUE, mec='white', mew=2, zorder=3)
ax1.text(np.degrees(h[i]), J[i] / 1000 + dy, txt, ha=ha, va='bottom', color=INK, fontsize=10)
ax1.annotate('', xy=(-64, 17), xytext=(-31, 25.5), arrowprops=dict(arrowstyle='->', color=MUTED, lw=1.5))
ax1.text(-88, 29.5, 'From a start beyond the ridge,\nlowering the cost means turning away', color=MUTED, fontsize=9.5, ha='left')
ax1.set_xlim(-90, 90); ax1.set_ylim(0, 33)
ax1.set_xlabel('Heading relative to the path (deg) away ← 0 → toward')
ax1.set_ylabel('Released MPC stage cost (×1000)')
ax1.set_title('(a) Released cost, car 2.0 m from the path', loc='left', color=INK, fontsize=12)
ax1.grid(axis='y', color=GRID, lw=0.8); ax1.set_axisbelow(True)
# (b) start map with B01 MPC outcomes
for k, col, ms, lab, z in (('ok', GRAY, 4, 'reached the tube', 1), ('noentry', ORANGE, 7, 'no entry, no divergence (wheel lock)', 3),
('div', BLUE, 7, 'left the path (divergence)', 4)):
g = [p for p in pts if p['cls'] == k]
ax2.plot([p['toward_deg'] for p in g], [p['d'] for p in g], 'o', ms=ms, color=col, mec='white', mew=1 if k == 'ok' else 1.5,
ls='none', label=f'{lab} ({len(g)})', zorder=z)
dgrid = np.linspace(1.5, 2.5, 50)
ax2.plot(-a_elong0(dgrid), dgrid, color=INK, lw=2)
ax2.plot(-a_ridge(dgrid), dgrid, color=INK, lw=1.5, ls='--')
ax2.text(-a_elong0(2.5) - 1, 2.53, 'reference point\nbehind the car', ha='right', va='bottom', fontsize=9.5, color=INK)
ax2.text(-a_ridge(1.5) + 1, 1.44, 'cost ridge (as in a)', ha='left', va='top', fontsize=9.5, color=INK)
ax2.set_xlim(-46, 46); ax2.set_ylim(1.38, 2.68)
ax2.set_xlabel('Start heading relative to the path (deg) away ← 0 → toward\n(offset and heading as the controller sees them at its first tick)', fontsize=10.5)
ax2.set_ylabel('Start offset |e| (m)')
ax2.set_title('(b) 400 TR starts, released MPC outcome', loc='left', color=INK, fontsize=12)
ax2.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), ncol=3, frameon=False, fontsize=9.5, handletextpad=0.2, columnspacing=1.0)
ax2.grid(color=GRID, lw=0.8); ax2.set_axisbelow(True)
fig.savefig(FIG, dpi=160, bbox_inches='tight')