26 KiB
26 KiB
In [ ]:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
np.set_printoptions(precision=5, suppress=True)In [ ]:
def rot_x(a):
c, s = np.cos(a), np.sin(a)
return np.array([[1.0, 0.0, 0.0],
[0.0, c, -s],
[0.0, s, c]])
def rot_y(a):
c, s = np.cos(a), np.sin(a)
return np.array([[ c, 0.0, s],
[0.0, 1.0, 0.0],
[-s, 0.0, c]])
def rot_z(a):
c, s = np.cos(a), np.sin(a)
return np.array([[c, -s, 0.0],
[s, c, 0.0],
[0.0, 0.0, 1.0]])
def R_zyx(yaw, pitch, roll):
return rot_z(yaw) @ rot_y(pitch) @ rot_x(roll)
def hat(w):
wx, wy, wz = np.asarray(w, dtype=float)
return np.array([[0.0, -wz, wy],
[wz, 0.0, -wx],
[-wy, wx, 0.0]])
def exp_so3(w):
w = np.asarray(w, dtype=float)
theta = np.linalg.norm(w)
W = hat(w)
if theta < 1e-8:
return np.eye(3) + W + 0.5 * (W @ W)
A = np.sin(theta) / theta
B = (1.0 - np.cos(theta)) / theta**2
return np.eye(3) + A * W + B * (W @ W)
def V_so3(w):
w = np.asarray(w, dtype=float)
theta = np.linalg.norm(w)
W = hat(w)
if theta < 1e-8:
return np.eye(3) + 0.5 * W + (1.0 / 6.0) * (W @ W)
B = (1.0 - np.cos(theta)) / theta**2
C = (theta - np.sin(theta)) / theta**3
return np.eye(3) + B * W + C * (W @ W)
def exp_se3(xi):
"""xi = [rho, omega] -> T in SE(3)."""
xi = np.asarray(xi, dtype=float)
rho, w = xi[:3], xi[3:]
T = np.eye(4)
T[:3, :3] = exp_so3(w)
T[:3, 3] = V_so3(w) @ rho
return T
def make_T(R, t):
T = np.eye(4)
T[:3, :3] = R
T[:3, 3] = t
return T
def transform_points(T, X):
R, t = T[:3, :3], T[:3, 3]
return (R @ X.T).T + t
def alignment_residual(T, X, Y):
"""Stacked residual [RX_i+t-Y_i], shape (3N,)."""
return (transform_points(T, X) - Y).reshape(-1)
def rotation_error_deg(R_est, R_true):
R_rel = R_est.T @ R_true
cos_angle = np.clip((np.trace(R_rel) - 1.0) / 2.0, -1.0, 1.0)
return float(np.degrees(np.arccos(cos_angle)))In [ ]:
N_POINTS = 40
X = rng.uniform(low=[-0.9, -0.7, -0.5], high=[1.0, 0.8, 0.9], size=(N_POINTS, 3))
TRUE_ANGLES = np.array([0.35, np.radians(86.0), -0.25])
R_true = R_zyx(*TRUE_ANGLES)
t_true = np.array([0.55, -0.35, 0.25])
T_true = make_T(R_true, t_true)
NOISE_STD = 0.015
Y_clean = transform_points(T_true, X)
Y = Y_clean + rng.normal(scale=NOISE_STD, size=Y_clean.shape)
print("points:", len(X))
print("noise std:", NOISE_STD)
print("cost at true pose:", 0.5 * np.sum(alignment_residual(T_true, X, Y) ** 2))In [ ]:
def euler_rotation_derivatives(yaw, pitch, roll):
"""
Аналитические производные Rz(yaw) @ Ry(pitch) @ Rx(roll).
Returns
-------
dR_dyaw, dR_dpitch, dR_droll : три матрицы shape (3, 3)
"""
# TODO: выведите производные элементарных Rx/Ry/Rz и примените правило произведения
raise NotImplementedError("TODO: см. подсказку выше")
def euler_rotation_jacobian_analytic(angles):
"""d vec(R) / d(yaw,pitch,roll), shape (9,3)."""
derivs = euler_rotation_derivatives(*angles)
return np.column_stack([dR.reshape(-1) for dR in derivs])
def euler_rotation_jacobian_numeric(angles, eps=1e-6):
"""Reference checker: central finite differences, shape (9,3)."""
J = np.zeros((9, 3))
for j in range(3):
d = np.zeros(3)
d[j] = eps
J[:, j] = (
R_zyx(*(angles + d)).reshape(-1)
- R_zyx(*(angles - d)).reshape(-1)
) / (2.0 * eps)
return JIn [ ]:
# Проверка аналитического якобиана и диагностика gimbal lock.
angles_check = np.array([0.3, 0.7, -0.4])
J_e_analytic = euler_rotation_jacobian_analytic(angles_check)
J_e_numeric = euler_rotation_jacobian_numeric(angles_check)
rel_err_euler = np.linalg.norm(J_e_analytic - J_e_numeric) / np.linalg.norm(J_e_numeric)
print("Euler Jacobian relative error:", rel_err_euler)
assert rel_err_euler < 1e-6, "Аналитический Euler Jacobian не совпадает с numerical checker"
pitches = np.radians(np.linspace(0.0, 89.95, 300))
sigma_min = []
condition = []
for pitch in pitches:
J = euler_rotation_jacobian_analytic(np.array([0.3, pitch, -0.4]))
s = np.linalg.svd(J, compute_uv=False)
sigma_min.append(s[-1])
condition.append(s[0] / s[-1])
fig, ax = plt.subplots(1, 2, figsize=(11, 3.8))
ax[0].plot(np.degrees(pitches), sigma_min)
ax[0].set_xlabel("pitch, deg")
ax[0].set_ylabel("smallest singular value")
ax[0].set_title("Euler Jacobian near gimbal lock")
ax[0].grid(alpha=0.3)
ax[1].semilogy(np.degrees(pitches), condition)
ax[1].set_xlabel("pitch, deg")
ax[1].set_ylabel("condition number")
ax[1].set_title("Conditioning of Euler coordinates")
ax[1].grid(alpha=0.3)
plt.tight_layout()
plt.show()In [ ]:
def numerical_pose_jacobian(T, X, eps=1e-6):
"""
Численный якобиан 3D–3D невязки по ПРАВОМУ возмущению
T @ Exp(delta_xi).
Поскольку Y — константа по delta_xi, производная residual совпадает
с производной transformed points. Используйте central finite differences.
Return shape (3*N, 6).
"""
# TODO: для каждого базисного направления сделайте +eps и -eps right perturbation
raise NotImplementedError("TODO: см. подсказку выше")In [ ]:
def analytic_pose_jacobian(T, X):
"""
Analytic Jacobian of stacked residuals RX_i+t-Y_i with respect to
RIGHT SE(3) perturbation xi=[rho, omega].
Return shape (3*N, 6).
"""
# TODO: используйте first-order Exp(delta_xi^) и hat(a)b = -hat(b)a
raise NotImplementedError("TODO: см. подсказку выше")оIn [ ]:
# Проверка analytic vs numerical.
T_check = make_T(
R_zyx(0.2, np.radians(55.0), -0.15),
np.array([0.2, -0.1, 0.3]),
)
J_se3_num = numerical_pose_jacobian(T_check, X)
J_se3_ana = analytic_pose_jacobian(T_check, X)
rel_err_se3 = np.linalg.norm(J_se3_ana - J_se3_num) / np.linalg.norm(J_se3_num)
print("SE(3) Jacobian relative error:", rel_err_se3)
assert rel_err_se3 < 2e-6, "Analytic SE(3) Jacobian не совпадает с numerical Jacobian"In [ ]:
def gauss_newton_se3(T0, X, Y, jacobian_fn, n_iter=10, damping=1e-8):
"""Gauss–Newton для правого SE(3) возмущения.
Return
------
T_est, cost_trace, condition_trace
"""
# TODO: реализуйте GN loop: residual, J, normal equations и update T <- T @ Exp(delta)
raise NotImplementedError("TODO: см. подсказку выше")
P0_LIE = np.array([0.20, np.radians(70.0), -0.10])
T0_lie = make_T(R_zyx(*P0_LIE), np.array([0.25, -0.15, 0.05]))
T_num, cost_num, _ = gauss_newton_se3(T0_lie, X, Y, numerical_pose_jacobian)
T_ana, cost_ana, _ = gauss_newton_se3(T0_lie, X, Y, analytic_pose_jacobian)
print("final cost, numerical J:", cost_num[-1])
print("final cost, analytic J:", cost_ana[-1])
print("||T_num - T_ana||:", np.linalg.norm(T_num - T_ana))
fig = plt.figure(figsize=(11, 4))
ax_cost = fig.add_subplot(1, 2, 1)
ax_cost.semilogy(cost_num, marker="o", label="numerical J")
ax_cost.semilogy(cost_ana, marker="s", label="analytic J")
ax_cost.set_xlabel("iteration")
ax_cost.set_ylabel("0.5 ||r||²")
ax_cost.set_title("Same SE(3) optimization, two Jacobians")
ax_cost.grid(alpha=0.3)
ax_cost.legend()
ax3d = fig.add_subplot(1, 2, 2, projection="3d")
Y_init = transform_points(T0_lie, X)
Y_est = transform_points(T_ana, X)
ax3d.scatter(*Y.T, s=18, label="target noisy Y")
ax3d.scatter(*Y_init.T, s=12, label="initial")
ax3d.scatter(*Y_est.T, s=12, label="estimated")
ax3d.set_title("3D–3D alignment")
ax3d.legend()
plt.tight_layout()
plt.show()In [ ]:
def euler_alignment_residual(params, X, Y):
"""
params = [tx, ty, tz, yaw, pitch, roll].
Return stacked residuals R(yaw,pitch,roll) X_i + t - Y_i,
shape (3*N,).
"""
# TODO: реализуйте функцию по условию выше
raise NotImplementedError("TODO: см. подсказку выше")
def euler_alignment_jacobian(params, X):
"""
Analytic Jacobian of euler_alignment_residual with respect to
[tx, ty, tz, yaw, pitch, roll].
Reuse euler_rotation_derivatives() from Task 1.
Return shape (3*N, 6).
"""
# TODO: соберите по каждой точке 3x6 block: translation + три angular columns
raise NotImplementedError("TODO: см. подсказку выше")
def gauss_newton_euler(params0, X, Y, n_iter=10, damping=1e-8):
"""
Gauss–Newton optimization in additive Euler coordinates.
Use euler_alignment_residual() and euler_alignment_jacobian().
Return:
params_est shape (6,)
cost_trace scalar objective history
condition_trace condition number of J at each iteration
params_trace history of parameter vectors, shape (n_iter+1, 6)
"""
# TODO: реализуйте полный GN loop и additive update params <- params + delta
raise NotImplementedError("TODO: см. подсказку выше")In [ ]:
# Быстрая numerical sanity-check для Task 3 Jacobian.
def numerical_euler_alignment_jacobian(params, X, eps=1e-6):
# Как и в Task 2, target Y не нужен: производная residual по params
# совпадает с производной предсказанных transformed points.
J = np.zeros((3 * len(X), 6))
def predict(p):
t = p[:3]
R = R_zyx(*p[3:])
return ((R @ X.T).T + t).reshape(-1)
for j in range(6):
d = np.zeros(6)
d[j] = eps
J[:, j] = (predict(params + d) - predict(params - d)) / (2.0 * eps)
return J
p_check = np.array([0.2, -0.1, 0.15, 0.3, np.radians(50.0), -0.2])
J3_ana = euler_alignment_jacobian(p_check, X)
J3_num = numerical_euler_alignment_jacobian(p_check, X)
rel_err_task3 = np.linalg.norm(J3_ana - J3_num) / np.linalg.norm(J3_num)
print("Euler alignment Jacobian relative error:", rel_err_task3)
assert rel_err_task3 < 2e-6In [ ]:
comparison_noise = Y - Y_clean
COMPARISON_CASES = {
"regular": {
"true_angles": np.array([0.35, np.radians(40.0), -0.25]),
"init_params": np.array([0.25, -0.15, 0.05, 0.20, np.radians(25.0), -0.10]),
},
"near gimbal": {
"true_angles": np.array([0.35, np.radians(89.9), -0.25]),
"init_params": np.array([0.25, -0.15, 0.05, 0.20, np.radians(89.999), -0.10]),
},
}
results = {}
for name, cfg in COMPARISON_CASES.items():
R_true_case = R_zyx(*cfg["true_angles"])
T_true_case = make_T(R_true_case, t_true)
Y_case = transform_points(T_true_case, X) + comparison_noise
p0 = cfg["init_params"]
p_est, cost_e, cond_e, params_trace = gauss_newton_euler(
p0, X, Y_case, n_iter=10, damping=1e-8
)
T0 = make_T(R_zyx(*p0[3:]), p0[:3])
T_est, cost_lie, cond_lie = gauss_newton_se3(
T0, X, Y_case, analytic_pose_jacobian, n_iter=10, damping=1e-8
)
euler_coordinate_step_deg = np.degrees(
np.linalg.norm(np.diff(params_trace[:, 3:], axis=0), axis=1)
)
euler_physical_step_deg = []
for p_prev, p_next in zip(params_trace[:-1], params_trace[1:]):
R_prev = R_zyx(*p_prev[3:])
R_next = R_zyx(*p_next[3:])
euler_physical_step_deg.append(rotation_error_deg(R_prev, R_next))
euler_physical_step_deg = np.asarray(euler_physical_step_deg)
R_e = R_zyx(*p_est[3:])
t_e = p_est[:3]
results[name] = {
"euler": {
"cost": cost_e,
"cond": cond_e,
"rot_err": rotation_error_deg(R_e, R_true_case),
"trans_err": np.linalg.norm(t_e - t_true),
"coord_step_deg": euler_coordinate_step_deg,
"physical_step_deg": euler_physical_step_deg,
"final_angles_deg": np.degrees(p_est[3:]),
},
"lie": {
"cost": cost_lie,
"cond": cond_lie,
"rot_err": rotation_error_deg(T_est[:3, :3], R_true_case),
"trans_err": np.linalg.norm(T_est[:3, 3] - t_true),
},
}
print(f"\n{name}")
for method in ("euler", "lie"):
out = results[name][method]
print(
f" {method:5s}: final cost={out['cost'][-1]:.6f}, "
f"rot err={out['rot_err']:.4f} deg, "
f"trans err={out['trans_err']:.5f}, "
f"initial cond(J)={out['cond'][0]:.2e}"
)
print(" Euler final angles [deg]:", results[name]["euler"]["final_angles_deg"])
print(
" max ||delta Euler|| [deg]:",
np.max(results[name]["euler"]["coord_step_deg"]),
)
print(
" max physical rotation step [deg]:",
np.max(results[name]["euler"]["physical_step_deg"]),
)In [ ]:
fig, ax = plt.subplots(3, 2, figsize=(11, 10))
for col, name in enumerate(COMPARISON_CASES):
for method in ("euler", "lie"):
ax[0, col].semilogy(results[name][method]["cost"], marker="o", label=method)
ax[0, col].set_title(f"{name}: objective")
ax[0, col].set_xlabel("iteration")
ax[0, col].set_ylabel("0.5 ||r||²")
ax[0, col].grid(alpha=0.3)
ax[0, col].legend()
for method in ("euler", "lie"):
ax[1, col].semilogy(results[name][method]["cond"], marker="o", label=method)
ax[1, col].set_title(f"{name}: Jacobian conditioning")
ax[1, col].set_xlabel("iteration")
ax[1, col].set_ylabel("cond(J)")
ax[1, col].grid(alpha=0.3)
ax[1, col].legend()
coord = np.maximum(results[name]["euler"]["coord_step_deg"], 1e-12)
physical = np.maximum(results[name]["euler"]["physical_step_deg"], 1e-12)
ax[2, col].semilogy(coord, marker="o", label=r"$||\Delta Euler||$")
ax[2, col].semilogy(physical, marker="s", label="physical rotation step")
ax[2, col].set_title(f"{name}: Euler coordinate step vs physical rotation")
ax[2, col].set_xlabel("iteration")
ax[2, col].set_ylabel("degrees")
ax[2, col].grid(alpha=0.3)
ax[2, col].legend()
plt.tight_layout()
plt.show()