Files
2026-09-14 12:03:11 +00:00

755 lines
26 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"id": "3ba11e8e",
"metadata": {},
"source": [
"# Домашнее задание 2 — Вращения, SE(3) и локальная оптимизация\n",
"\n",
"**Курс:** 3D Computer Vision & Graphics · **к паре 2:** геометрия вращений и позы\n",
"\n",
"По двум соответствующим 3D point clouds восстановите rigid transform\n",
"\n",
"$$\n",
"Y_i \\approx R X_i + t.\n",
"$$\n",
"\n",
"В заданиях используются Euler coordinates, правые $SE(3)$-приращения и Gauss–Newton.\n",
"Места для реализации отмечены `TODO` в student-версии."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "06c981df",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"rng = np.random.default_rng(42)\n",
"np.set_printoptions(precision=5, suppress=True)"
]
},
{
"cell_type": "markdown",
"id": "ec5f2e57",
"metadata": {},
"source": [
"## Вспомогательные функции: вращения, SE(3) и synthetic point cloud\n",
"\n",
"Эти функции даны готовыми и не являются частью задания.\n",
"\n",
"Используем convention\n",
"\n",
"$$\n",
"R(\\psi,\\theta,\\phi)=R_z(\\psi)R_y(\\theta)R_x(\\phi),\n",
"$$\n",
"\n",
"а для шага оптимизации через Ли — **правое возмущение**\n",
"\n",
"$$\n",
"T_{new}=T\\exp(\\delta\\xi^\\wedge),\n",
"\\qquad\n",
"\\delta\\xi=(\\delta\\rho,\\delta\\omega)\\in\\mathbb R^6.\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f0697e05",
"metadata": {},
"outputs": [],
"source": [
"def rot_x(a):\n",
" c, s = np.cos(a), np.sin(a)\n",
" return np.array([[1.0, 0.0, 0.0],\n",
" [0.0, c, -s],\n",
" [0.0, s, c]])\n",
"\n",
"\n",
"def rot_y(a):\n",
" c, s = np.cos(a), np.sin(a)\n",
" return np.array([[ c, 0.0, s],\n",
" [0.0, 1.0, 0.0],\n",
" [-s, 0.0, c]])\n",
"\n",
"\n",
"def rot_z(a):\n",
" c, s = np.cos(a), np.sin(a)\n",
" return np.array([[c, -s, 0.0],\n",
" [s, c, 0.0],\n",
" [0.0, 0.0, 1.0]])\n",
"\n",
"\n",
"def R_zyx(yaw, pitch, roll):\n",
" return rot_z(yaw) @ rot_y(pitch) @ rot_x(roll)\n",
"\n",
"\n",
"def hat(w):\n",
" wx, wy, wz = np.asarray(w, dtype=float)\n",
" return np.array([[0.0, -wz, wy],\n",
" [wz, 0.0, -wx],\n",
" [-wy, wx, 0.0]])\n",
"\n",
"\n",
"def exp_so3(w):\n",
" w = np.asarray(w, dtype=float)\n",
" theta = np.linalg.norm(w)\n",
" W = hat(w)\n",
" if theta < 1e-8:\n",
" return np.eye(3) + W + 0.5 * (W @ W)\n",
" A = np.sin(theta) / theta\n",
" B = (1.0 - np.cos(theta)) / theta**2\n",
" return np.eye(3) + A * W + B * (W @ W)\n",
"\n",
"\n",
"def V_so3(w):\n",
" w = np.asarray(w, dtype=float)\n",
" theta = np.linalg.norm(w)\n",
" W = hat(w)\n",
" if theta < 1e-8:\n",
" return np.eye(3) + 0.5 * W + (1.0 / 6.0) * (W @ W)\n",
" B = (1.0 - np.cos(theta)) / theta**2\n",
" C = (theta - np.sin(theta)) / theta**3\n",
" return np.eye(3) + B * W + C * (W @ W)\n",
"\n",
"\n",
"def exp_se3(xi):\n",
" \"\"\"xi = [rho, omega] -> T in SE(3).\"\"\"\n",
" xi = np.asarray(xi, dtype=float)\n",
" rho, w = xi[:3], xi[3:]\n",
" T = np.eye(4)\n",
" T[:3, :3] = exp_so3(w)\n",
" T[:3, 3] = V_so3(w) @ rho\n",
" return T\n",
"\n",
"\n",
"def make_T(R, t):\n",
" T = np.eye(4)\n",
" T[:3, :3] = R\n",
" T[:3, 3] = t\n",
" return T\n",
"\n",
"\n",
"def transform_points(T, X):\n",
" R, t = T[:3, :3], T[:3, 3]\n",
" return (R @ X.T).T + t\n",
"\n",
"\n",
"def alignment_residual(T, X, Y):\n",
" \"\"\"Stacked residual [RX_i+t-Y_i], shape (3N,).\"\"\"\n",
" return (transform_points(T, X) - Y).reshape(-1)\n",
"\n",
"\n",
"def rotation_error_deg(R_est, R_true):\n",
" R_rel = R_est.T @ R_true\n",
" cos_angle = np.clip((np.trace(R_rel) - 1.0) / 2.0, -1.0, 1.0)\n",
" return float(np.degrees(np.arccos(cos_angle)))"
]
},
{
"cell_type": "markdown",
"id": "fb5b8c2e",
"metadata": {},
"source": [
"### Данные\n",
"\n",
"Истинное target cloud получаем из source cloud известной pose и добавляем небольшой Гауссовский шум:\n",
"\n",
"$$\n",
"Y_i=R_{true}X_i+t_{true}+\\varepsilon_i,\n",
"\\qquad\n",
"\\varepsilon_i\\sim\\mathcal N(0,\\sigma^2I).\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0131fa72",
"metadata": {},
"outputs": [],
"source": [
"N_POINTS = 40\n",
"X = rng.uniform(low=[-0.9, -0.7, -0.5], high=[1.0, 0.8, 0.9], size=(N_POINTS, 3))\n",
"\n",
"TRUE_ANGLES = np.array([0.35, np.radians(86.0), -0.25])\n",
"R_true = R_zyx(*TRUE_ANGLES)\n",
"t_true = np.array([0.55, -0.35, 0.25])\n",
"T_true = make_T(R_true, t_true)\n",
"\n",
"NOISE_STD = 0.015\n",
"Y_clean = transform_points(T_true, X)\n",
"Y = Y_clean + rng.normal(scale=NOISE_STD, size=Y_clean.shape)\n",
"\n",
"print(\"points:\", len(X))\n",
"print(\"noise std:\", NOISE_STD)\n",
"print(\"cost at true pose:\", 0.5 * np.sum(alignment_residual(T_true, X, Y) ** 2))"
]
},
{
"cell_type": "markdown",
"id": "b1749957",
"metadata": {},
"source": [
"## Задание 1. Якобиан для углов Эйлера: аналитика → численная проверка → gimbal lock\n",
"\n",
"Для\n",
"\n",
"$$\n",
"R(\\psi,\\theta,\\phi)=R_z(\\psi)R_y(\\theta)R_x(\\phi)\n",
"$$\n",
"\n",
"выведите и реализуйте три матрицы\n",
"\n",
"$$\n",
"\\frac{\\partial R}{\\partial\\psi},\\qquad\n",
"\\frac{\\partial R}{\\partial\\theta},\\qquad\n",
"\\frac{\\partial R}{\\partial\\phi}.\n",
"$$\n",
"\n",
"Подсказка: используйте обычное правило производной произведения, например\n",
"\n",
"$$\n",
"\\frac{\\partial R}{\\partial\\psi}\n",
"=R_z'(\\psi)R_y(\\theta)R_x(\\phi).\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4d7454af",
"metadata": {},
"outputs": [],
"source": [
"def euler_rotation_derivatives(yaw, pitch, roll):\n",
" \"\"\"\n",
" Аналитические производные Rz(yaw) @ Ry(pitch) @ Rx(roll).\n",
"\n",
" Returns\n",
" -------\n",
" dR_dyaw, dR_dpitch, dR_droll : три матрицы shape (3, 3)\n",
" \"\"\"\n",
" # TODO: выведите производные элементарных Rx/Ry/Rz и примените правило произведения\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")\n",
"\n",
"\n",
"def euler_rotation_jacobian_analytic(angles):\n",
" \"\"\"d vec(R) / d(yaw,pitch,roll), shape (9,3).\"\"\"\n",
" derivs = euler_rotation_derivatives(*angles)\n",
" return np.column_stack([dR.reshape(-1) for dR in derivs])\n",
"\n",
"\n",
"def euler_rotation_jacobian_numeric(angles, eps=1e-6):\n",
" \"\"\"Reference checker: central finite differences, shape (9,3).\"\"\"\n",
" J = np.zeros((9, 3))\n",
" for j in range(3):\n",
" d = np.zeros(3)\n",
" d[j] = eps\n",
" J[:, j] = (\n",
" R_zyx(*(angles + d)).reshape(-1)\n",
" - R_zyx(*(angles - d)).reshape(-1)\n",
" ) / (2.0 * eps)\n",
" return J"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aae84489",
"metadata": {},
"outputs": [],
"source": [
"# Проверка аналитического якобиана и диагностика gimbal lock.\n",
"angles_check = np.array([0.3, 0.7, -0.4])\n",
"J_e_analytic = euler_rotation_jacobian_analytic(angles_check)\n",
"J_e_numeric = euler_rotation_jacobian_numeric(angles_check)\n",
"rel_err_euler = np.linalg.norm(J_e_analytic - J_e_numeric) / np.linalg.norm(J_e_numeric)\n",
"\n",
"print(\"Euler Jacobian relative error:\", rel_err_euler)\n",
"assert rel_err_euler < 1e-6, \"Аналитический Euler Jacobian не совпадает с numerical checker\"\n",
"\n",
"pitches = np.radians(np.linspace(0.0, 89.95, 300))\n",
"sigma_min = []\n",
"condition = []\n",
"\n",
"for pitch in pitches:\n",
" J = euler_rotation_jacobian_analytic(np.array([0.3, pitch, -0.4]))\n",
" s = np.linalg.svd(J, compute_uv=False)\n",
" sigma_min.append(s[-1])\n",
" condition.append(s[0] / s[-1])\n",
"\n",
"fig, ax = plt.subplots(1, 2, figsize=(11, 3.8))\n",
"ax[0].plot(np.degrees(pitches), sigma_min)\n",
"ax[0].set_xlabel(\"pitch, deg\")\n",
"ax[0].set_ylabel(\"smallest singular value\")\n",
"ax[0].set_title(\"Euler Jacobian near gimbal lock\")\n",
"ax[0].grid(alpha=0.3)\n",
"\n",
"ax[1].semilogy(np.degrees(pitches), condition)\n",
"ax[1].set_xlabel(\"pitch, deg\")\n",
"ax[1].set_ylabel(\"condition number\")\n",
"ax[1].set_title(\"Conditioning of Euler coordinates\")\n",
"ax[1].grid(alpha=0.3)\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "50757c76",
"metadata": {},
"source": [
"## Задание 2. Якобиан 3D–3D невязки по $SE(3)$ возмущению\n",
"\n",
"На текущей pose $T$ рассматриваем локальную невязку\n",
"\n",
"$$\n",
"\\tilde r(\\delta\\xi)\n",
"=r\\!\\left(T\\exp(\\delta\\xi^\\wedge)\\right).\n",
"$$\n",
"\n",
"Для одной точки\n",
"\n",
"$$\n",
"r_i(T)=RX_i+t-Y_i.\n",
"$$\n",
"\n",
"### 2a. Numerical Jacobian\n",
"\n",
"Реализуйте численный якобиан через центрированную конечную разность по шести направлениям $e_j\\in\\mathbb R^6$:\n",
"\n",
"$$\n",
"J_{:,j}\\approx\n",
"\\frac{\n",
"r(T\\exp((+\\varepsilon e_j)^\\wedge))\n",
"-\n",
"r(T\\exp((-\\varepsilon e_j)^\\wedge))\n",
"}{2\\varepsilon}.\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6717cd5c",
"metadata": {},
"outputs": [],
"source": [
"def numerical_pose_jacobian(T, X, eps=1e-6):\n",
" \"\"\"\n",
" Численный якобиан 3D–3D невязки по ПРАВОМУ возмущению\n",
" T @ Exp(delta_xi).\n",
"\n",
" Поскольку Y — константа по delta_xi, производная residual совпадает\n",
" с производной transformed points. Используйте central finite differences.\n",
"\n",
" Return shape (3*N, 6).\n",
" \"\"\"\n",
" # TODO: для каждого базисного направления сделайте +eps и -eps right perturbation\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")"
]
},
{
"cell_type": "markdown",
"id": "6c26d42b",
"metadata": {},
"source": [
"### 2b. Аналитический якобиан\n",
"\n",
"Выведите аналитический якобиан той же невязки для **правого возмущения**. Добавьте вывод в markdown ячейку.\n",
"\n",
"Достаточно двух фактов из семинара:\n",
"\n",
"$$\n",
"\\exp(\\delta\\xi^\\wedge)\\approx I+\\delta\\xi^\\wedge,\n",
"$$\n",
"\n",
"и\n",
"\n",
"$$\n",
"\\widehat a\\,b=-\\widehat b\\,a.\n",
"$$\n",
"\n",
"Получите изменение одной transformed point в первом порядке и из него соберите блок\n",
"$J_i\\in\\mathbb R^{3\\times6}$. "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9825d797",
"metadata": {},
"outputs": [],
"source": [
"def analytic_pose_jacobian(T, X):\n",
" \"\"\"\n",
" Analytic Jacobian of stacked residuals RX_i+t-Y_i with respect to\n",
" RIGHT SE(3) perturbation xi=[rho, omega].\n",
"\n",
" Return shape (3*N, 6).\n",
" \"\"\"\n",
" # TODO: используйте first-order Exp(delta_xi^) и hat(a)b = -hat(b)a\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")о"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14e7d639",
"metadata": {},
"outputs": [],
"source": [
"# Проверка analytic vs numerical.\n",
"T_check = make_T(\n",
" R_zyx(0.2, np.radians(55.0), -0.15),\n",
" np.array([0.2, -0.1, 0.3]),\n",
")\n",
"\n",
"J_se3_num = numerical_pose_jacobian(T_check, X)\n",
"J_se3_ana = analytic_pose_jacobian(T_check, X)\n",
"rel_err_se3 = np.linalg.norm(J_se3_ana - J_se3_num) / np.linalg.norm(J_se3_num)\n",
"\n",
"print(\"SE(3) Jacobian relative error:\", rel_err_se3)\n",
"assert rel_err_se3 < 2e-6, \"Analytic SE(3) Jacobian не совпадает с numerical Jacobian\""
]
},
{
"cell_type": "markdown",
"id": "8a61c198",
"metadata": {},
"source": [
"### Используем оба якобиана в одном и том же Gauss–Newton solver\n",
"\n",
"Реализуйте Gauss–Newton solver для правого $SE(3)$ возмущения и сравните результаты\n",
"для двух реализаций $J$."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fe4fdcb1",
"metadata": {},
"outputs": [],
"source": [
"def gauss_newton_se3(T0, X, Y, jacobian_fn, n_iter=10, damping=1e-8):\n",
" \"\"\"Gauss–Newton для правого SE(3) возмущения.\n",
"\n",
" Return\n",
" ------\n",
" T_est, cost_trace, condition_trace\n",
" \"\"\"\n",
" # TODO: реализуйте GN loop: residual, J, normal equations и update T <- T @ Exp(delta)\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")\n",
"\n",
"\n",
"P0_LIE = np.array([0.20, np.radians(70.0), -0.10])\n",
"T0_lie = make_T(R_zyx(*P0_LIE), np.array([0.25, -0.15, 0.05]))\n",
"\n",
"T_num, cost_num, _ = gauss_newton_se3(T0_lie, X, Y, numerical_pose_jacobian)\n",
"T_ana, cost_ana, _ = gauss_newton_se3(T0_lie, X, Y, analytic_pose_jacobian)\n",
"\n",
"print(\"final cost, numerical J:\", cost_num[-1])\n",
"print(\"final cost, analytic J:\", cost_ana[-1])\n",
"print(\"||T_num - T_ana||:\", np.linalg.norm(T_num - T_ana))\n",
"\n",
"fig = plt.figure(figsize=(11, 4))\n",
"ax_cost = fig.add_subplot(1, 2, 1)\n",
"ax_cost.semilogy(cost_num, marker=\"o\", label=\"numerical J\")\n",
"ax_cost.semilogy(cost_ana, marker=\"s\", label=\"analytic J\")\n",
"ax_cost.set_xlabel(\"iteration\")\n",
"ax_cost.set_ylabel(\"0.5 ||r||²\")\n",
"ax_cost.set_title(\"Same SE(3) optimization, two Jacobians\")\n",
"ax_cost.grid(alpha=0.3)\n",
"ax_cost.legend()\n",
"\n",
"ax3d = fig.add_subplot(1, 2, 2, projection=\"3d\")\n",
"Y_init = transform_points(T0_lie, X)\n",
"Y_est = transform_points(T_ana, X)\n",
"ax3d.scatter(*Y.T, s=18, label=\"target noisy Y\")\n",
"ax3d.scatter(*Y_init.T, s=12, label=\"initial\")\n",
"ax3d.scatter(*Y_est.T, s=12, label=\"estimated\")\n",
"ax3d.set_title(\"3D–3D alignment\")\n",
"ax3d.legend()\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "44eb673f",
"metadata": {},
"source": [
"## Задание 3. Та же задача alignment в 3D через угла Эйлера\n",
"\n",
"Теперь состояние — обычный вектор из шести параметров: три координаты переноса + три угла Эйлера.\n",
"\n",
"$$\n",
"p=(t_x,t_y,t_z,\\psi,\\theta,\\phi)\\in\\mathbb R^6.\n",
"$$\n",
"\n",
"Реализуйте три функции ниже самостоятельно.\n",
"\n",
"Для якобиана одной точки используйте chain rule (производная сложной функции) и производные из **Задания 1**:\n",
"\n",
"$$\n",
"r_i(p)=R(\\psi,\\theta,\\phi)X_i+t-Y_i.\n",
"$$\n",
"\n",
"Первые три столбца отвечают переносу, следующие три — влиянию yaw/pitch/roll.\n",
"\n",
"Для Gauss–Newton используйте\n",
"\n",
"$$\n",
"(J^TJ+\\lambda I)\\Delta p=-J^Tr,\n",
"\\qquad\n",
"p\\leftarrow p+\\Delta p.\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ed6dfd51",
"metadata": {},
"outputs": [],
"source": [
"def euler_alignment_residual(params, X, Y):\n",
" \"\"\"\n",
" params = [tx, ty, tz, yaw, pitch, roll].\n",
"\n",
" Return stacked residuals R(yaw,pitch,roll) X_i + t - Y_i,\n",
" shape (3*N,).\n",
" \"\"\"\n",
" # TODO: реализуйте функцию по условию выше\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")\n",
"\n",
"\n",
"def euler_alignment_jacobian(params, X):\n",
" \"\"\"\n",
" Analytic Jacobian of euler_alignment_residual with respect to\n",
" [tx, ty, tz, yaw, pitch, roll].\n",
"\n",
" Reuse euler_rotation_derivatives() from Task 1.\n",
" Return shape (3*N, 6).\n",
" \"\"\"\n",
" # TODO: соберите по каждой точке 3x6 block: translation + три angular columns\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")\n",
"\n",
"\n",
"def gauss_newton_euler(params0, X, Y, n_iter=10, damping=1e-8):\n",
" \"\"\"\n",
" Gauss–Newton optimization in additive Euler coordinates.\n",
"\n",
" Use euler_alignment_residual() and euler_alignment_jacobian().\n",
" Return:\n",
" params_est shape (6,)\n",
" cost_trace scalar objective history\n",
" condition_trace condition number of J at each iteration\n",
" params_trace history of parameter vectors, shape (n_iter+1, 6)\n",
" \"\"\"\n",
" # TODO: реализуйте полный GN loop и additive update params <- params + delta\n",
" raise NotImplementedError(\"TODO: см. подсказку выше\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "10f30fc6",
"metadata": {},
"outputs": [],
"source": [
"# Быстрая numerical sanity-check для Task 3 Jacobian.\n",
"def numerical_euler_alignment_jacobian(params, X, eps=1e-6):\n",
" # Как и в Task 2, target Y не нужен: производная residual по params\n",
" # совпадает с производной предсказанных transformed points.\n",
" J = np.zeros((3 * len(X), 6))\n",
"\n",
" def predict(p):\n",
" t = p[:3]\n",
" R = R_zyx(*p[3:])\n",
" return ((R @ X.T).T + t).reshape(-1)\n",
"\n",
" for j in range(6):\n",
" d = np.zeros(6)\n",
" d[j] = eps\n",
" J[:, j] = (predict(params + d) - predict(params - d)) / (2.0 * eps)\n",
" return J\n",
"\n",
"\n",
"p_check = np.array([0.2, -0.1, 0.15, 0.3, np.radians(50.0), -0.2])\n",
"J3_ana = euler_alignment_jacobian(p_check, X)\n",
"J3_num = numerical_euler_alignment_jacobian(p_check, X)\n",
"rel_err_task3 = np.linalg.norm(J3_ana - J3_num) / np.linalg.norm(J3_num)\n",
"print(\"Euler alignment Jacobian relative error:\", rel_err_task3)\n",
"assert rel_err_task3 < 2e-6"
]
},
{
"cell_type": "markdown",
"id": "c444aee4",
"metadata": {},
"source": [
"### Сравнение: regular pose и pose около gimbal lock\n",
"\n",
"Сравните поведение Euler- и Lie-параметризаций для pitch $=40^\\circ$ и pitch $=89.9^\\circ$.\n",
"Используется один source cloud и одна реализация Gaussian noise."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "10145944",
"metadata": {},
"outputs": [],
"source": [
"comparison_noise = Y - Y_clean\n",
"\n",
"COMPARISON_CASES = {\n",
" \"regular\": {\n",
" \"true_angles\": np.array([0.35, np.radians(40.0), -0.25]),\n",
" \"init_params\": np.array([0.25, -0.15, 0.05, 0.20, np.radians(25.0), -0.10]),\n",
" },\n",
" \"near gimbal\": {\n",
" \"true_angles\": np.array([0.35, np.radians(89.9), -0.25]),\n",
" \"init_params\": np.array([0.25, -0.15, 0.05, 0.20, np.radians(89.999), -0.10]),\n",
" },\n",
"}\n",
"\n",
"results = {}\n",
"\n",
"for name, cfg in COMPARISON_CASES.items():\n",
" R_true_case = R_zyx(*cfg[\"true_angles\"])\n",
" T_true_case = make_T(R_true_case, t_true)\n",
" Y_case = transform_points(T_true_case, X) + comparison_noise\n",
" p0 = cfg[\"init_params\"]\n",
"\n",
" p_est, cost_e, cond_e, params_trace = gauss_newton_euler(\n",
" p0, X, Y_case, n_iter=10, damping=1e-8\n",
" )\n",
"\n",
" T0 = make_T(R_zyx(*p0[3:]), p0[:3])\n",
" T_est, cost_lie, cond_lie = gauss_newton_se3(\n",
" T0, X, Y_case, analytic_pose_jacobian, n_iter=10, damping=1e-8\n",
" )\n",
"\n",
" euler_coordinate_step_deg = np.degrees(\n",
" np.linalg.norm(np.diff(params_trace[:, 3:], axis=0), axis=1)\n",
" )\n",
"\n",
" euler_physical_step_deg = []\n",
" for p_prev, p_next in zip(params_trace[:-1], params_trace[1:]):\n",
" R_prev = R_zyx(*p_prev[3:])\n",
" R_next = R_zyx(*p_next[3:])\n",
" euler_physical_step_deg.append(rotation_error_deg(R_prev, R_next))\n",
" euler_physical_step_deg = np.asarray(euler_physical_step_deg)\n",
"\n",
" R_e = R_zyx(*p_est[3:])\n",
" t_e = p_est[:3]\n",
"\n",
" results[name] = {\n",
" \"euler\": {\n",
" \"cost\": cost_e,\n",
" \"cond\": cond_e,\n",
" \"rot_err\": rotation_error_deg(R_e, R_true_case),\n",
" \"trans_err\": np.linalg.norm(t_e - t_true),\n",
" \"coord_step_deg\": euler_coordinate_step_deg,\n",
" \"physical_step_deg\": euler_physical_step_deg,\n",
" \"final_angles_deg\": np.degrees(p_est[3:]),\n",
" },\n",
" \"lie\": {\n",
" \"cost\": cost_lie,\n",
" \"cond\": cond_lie,\n",
" \"rot_err\": rotation_error_deg(T_est[:3, :3], R_true_case),\n",
" \"trans_err\": np.linalg.norm(T_est[:3, 3] - t_true),\n",
" },\n",
" }\n",
"\n",
" print(f\"\\n{name}\")\n",
" for method in (\"euler\", \"lie\"):\n",
" out = results[name][method]\n",
" print(\n",
" f\" {method:5s}: final cost={out['cost'][-1]:.6f}, \"\n",
" f\"rot err={out['rot_err']:.4f} deg, \"\n",
" f\"trans err={out['trans_err']:.5f}, \"\n",
" f\"initial cond(J)={out['cond'][0]:.2e}\"\n",
" )\n",
"\n",
" print(\" Euler final angles [deg]:\", results[name][\"euler\"][\"final_angles_deg\"])\n",
" print(\n",
" \" max ||delta Euler|| [deg]:\",\n",
" np.max(results[name][\"euler\"][\"coord_step_deg\"]),\n",
" )\n",
" print(\n",
" \" max physical rotation step [deg]:\",\n",
" np.max(results[name][\"euler\"][\"physical_step_deg\"]),\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "befc5051",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(3, 2, figsize=(11, 10))\n",
"\n",
"for col, name in enumerate(COMPARISON_CASES):\n",
" for method in (\"euler\", \"lie\"):\n",
" ax[0, col].semilogy(results[name][method][\"cost\"], marker=\"o\", label=method)\n",
"\n",
" ax[0, col].set_title(f\"{name}: objective\")\n",
" ax[0, col].set_xlabel(\"iteration\")\n",
" ax[0, col].set_ylabel(\"0.5 ||r||²\")\n",
" ax[0, col].grid(alpha=0.3)\n",
" ax[0, col].legend()\n",
"\n",
" for method in (\"euler\", \"lie\"):\n",
" ax[1, col].semilogy(results[name][method][\"cond\"], marker=\"o\", label=method)\n",
"\n",
" ax[1, col].set_title(f\"{name}: Jacobian conditioning\")\n",
" ax[1, col].set_xlabel(\"iteration\")\n",
" ax[1, col].set_ylabel(\"cond(J)\")\n",
" ax[1, col].grid(alpha=0.3)\n",
" ax[1, col].legend()\n",
"\n",
" coord = np.maximum(results[name][\"euler\"][\"coord_step_deg\"], 1e-12)\n",
" physical = np.maximum(results[name][\"euler\"][\"physical_step_deg\"], 1e-12)\n",
"\n",
" ax[2, col].semilogy(coord, marker=\"o\", label=r\"$||\\Delta Euler||$\")\n",
" ax[2, col].semilogy(physical, marker=\"s\", label=\"physical rotation step\")\n",
"\n",
" ax[2, col].set_title(f\"{name}: Euler coordinate step vs physical rotation\")\n",
" ax[2, col].set_xlabel(\"iteration\")\n",
" ax[2, col].set_ylabel(\"degrees\")\n",
" ax[2, col].grid(alpha=0.3)\n",
" ax[2, col].legend()\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}