276 KiB
276 KiB
In [ ]:
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.io as pio
np.set_printoptions(precision=4, suppress=True)
pio.renderers.default = "plotly_mimetype+notebook"
In [ ]:
# Служебный код визуализации.
# На семинаре его внутреннюю реализацию разбирать не требуется:
# он нужен только для постановки сквозной задачи.
_HOUSE_POINTS = np.array([
[-0.8, -0.6, 0.0],
[ 0.8, -0.6, 0.0],
[ 0.8, 0.6, 0.0],
[-0.8, 0.6, 0.0],
[-0.8, -0.6, 1.0],
[ 0.8, -0.6, 1.0],
[ 0.8, 0.6, 1.0],
[-0.8, 0.6, 1.0],
[ 0.0, -0.6, 1.55],
[ 0.0, 0.6, 1.55],
], dtype=float)
_HOUSE_EDGES = [
(0, 1), (1, 2), (2, 3), (3, 0),
(4, 5), (5, 6), (6, 7), (7, 4),
(0, 4), (1, 5), (2, 6), (3, 7),
(4, 8), (5, 8), (7, 9), (6, 9), (8, 9),
]
def _look_at_world_to_camera(camera_position, target):
"""Строит одну удобную для demo ориентацию камеры, смотрящей на target."""
C = np.asarray(camera_position, dtype=float)
target = np.asarray(target, dtype=float)
world_up = np.array([0.0, 0.0, 1.0])
z_cam = target - C
z_cam /= np.linalg.norm(z_cam)
x_cam = np.cross(world_up, z_cam)
x_cam /= np.linalg.norm(x_cam)
y_cam = np.cross(z_cam, x_cam)
R_cw = np.vstack([x_cam, y_cam, z_cam])
t_cw = -R_cw @ C
return R_cw, t_cw
def _project_for_demo(X_world, R_cw, t_cw, K):
X_cam = X_world @ R_cw.T + t_cw
if np.any(X_cam[:, 2] <= 0):
raise ValueError("Часть объекта оказалась позади камеры.")
homogeneous_image = X_cam @ K.T
uv = homogeneous_image[:, :2] / homogeneous_image[:, 2:3]
return X_cam, uv
def _segments3d(points, edges):
out = []
for i, j in edges:
out.extend([points[i], points[j], [np.nan, np.nan, np.nan]])
return np.asarray(out, dtype=float)
def _segments2d(points, edges):
out = []
for i, j in edges:
out.extend([points[i], points[j], [np.nan, np.nan]])
return np.asarray(out, dtype=float)
def _camera_frustum_world(C, R_cw, K, image_size=(640, 480), depth=0.9):
width, height = image_size
corners_px = np.array([
[0, 0, 1],
[width, 0, 1],
[width, height, 1],
[0, height, 1],
], dtype=float)
rays_cam = corners_px @ np.linalg.inv(K).T
rays_cam = rays_cam / rays_cam[:, 2:3] * depth
# Для row-vector записи: camera -> world.
return rays_cam @ R_cw + C
def show_forward_problem(
camera_position=(3.2, -4.0, 2.6),
look_at=(0.0, 0.0, 0.65),
show_projection_rays=True,
):
"""Показывает одну и ту же сцену в world space и на изображении."""
C = np.asarray(camera_position, dtype=float)
target = np.asarray(look_at, dtype=float)
R_cw, t_cw = _look_at_world_to_camera(C, target)
# Для intro берём фиксированную простую pinhole-камеру.
# Минус в fy нужен только для привычного направления pixel-v вниз.
K = np.array([
[500.0, 0.0, 320.0],
[ 0.0, -500.0, 240.0],
[ 0.0, 0.0, 1.0],
])
_, uv = _project_for_demo(_HOUSE_POINTS, R_cw, t_cw, K)
fig = make_subplots(
rows=1,
cols=2,
specs=[[{"type": "scene"}, {"type": "xy"}]],
column_widths=[0.58, 0.42],
subplot_titles=(
"Мировая сцена и произвольно ориентированная камера",
"То, что наблюдает камера",
),
)
object_segments = _segments3d(_HOUSE_POINTS, _HOUSE_EDGES)
fig.add_trace(
go.Scatter3d(
x=object_segments[:, 0],
y=object_segments[:, 1],
z=object_segments[:, 2],
mode="lines",
name="3D object",
showlegend=False,
),
row=1, col=1,
)
fig.add_trace(
go.Scatter3d(
x=_HOUSE_POINTS[:, 0],
y=_HOUSE_POINTS[:, 1],
z=_HOUSE_POINTS[:, 2],
mode="markers+text",
text=[f"P{i}" for i in range(len(_HOUSE_POINTS))],
textposition="top center",
name="3D points",
),
row=1, col=1,
)
frustum = _camera_frustum_world(C, R_cw, K)
frustum_segments = []
for i in range(4):
frustum_segments.extend([C, frustum[i], [np.nan, np.nan, np.nan]])
for i in range(4):
frustum_segments.extend([
frustum[i],
frustum[(i + 1) % 4],
[np.nan, np.nan, np.nan],
])
frustum_segments = np.asarray(frustum_segments, dtype=float)
fig.add_trace(
go.Scatter3d(
x=frustum_segments[:, 0],
y=frustum_segments[:, 1],
z=frustum_segments[:, 2],
mode="lines",
name="camera frustum",
),
row=1, col=1,
)
# Локальные оси камеры.
axis_length = 0.7
axes_world = C + (np.eye(3) * axis_length) @ R_cw
for endpoint, label in zip(axes_world, ["x_c", "y_c", "z_c"]):
fig.add_trace(
go.Scatter3d(
x=[C[0], endpoint[0]],
y=[C[1], endpoint[1]],
z=[C[2], endpoint[2]],
mode="lines+text",
text=["", label],
showlegend=False,
name=label,
),
row=1, col=1,
)
if show_projection_rays:
for idx in [0, 2, 6, 8]:
p = _HOUSE_POINTS[idx]
fig.add_trace(
go.Scatter3d(
x=[C[0], p[0]],
y=[C[1], p[1]],
z=[C[2], p[2]],
mode="lines",
opacity=0.35,
showlegend=False,
),
row=1, col=1,
)
image_segments = _segments2d(uv, _HOUSE_EDGES)
fig.add_trace(
go.Scatter(
x=image_segments[:, 0],
y=image_segments[:, 1],
mode="lines",
showlegend=False,
name="projection",
),
row=1, col=2,
)
fig.add_trace(
go.Scatter(
x=uv[:, 0],
y=uv[:, 1],
mode="markers+text",
text=[f"P{i}" for i in range(len(uv))],
textposition="top center",
showlegend=False,
name="image points",
),
row=1, col=2,
)
fig.update_scenes(
aspectmode="data",
xaxis_title="X_w",
yaxis_title="Y_w",
zaxis_title="Z_w",
)
fig.update_xaxes(title_text="u [px]", range=[0, 640], row=1, col=2)
fig.update_yaxes(
title_text="v [px]",
range=[480, 0],
scaleanchor="x2",
scaleratio=1,
row=1, col=2,
)
fig.update_layout(
width=1150,
height=620,
margin=dict(l=20, r=20, t=70, b=20),
)
fig.show()
return R_cw, t_cwIn [ ]:
np.asarray(_HOUSE_POINTS).shapeIn [ ]:
# Единственная ячейка Block 0, с которой предлагается немного поэкспериментировать.
# Измените CAMERA_POSITION и перезапустите ячейку.
CAMERA_POSITION = (5, -4.0, 0)
LOOK_AT = (0.0, 0.5, 0.65)
R_demo, t_demo = show_forward_problem(
camera_position=CAMERA_POSITION,
look_at=LOOK_AT,
)
print("R =")
print(R_demo)
print("\nt =", t_demo)
In [ ]:
def rot_x(angle):
c, s = np.cos(angle), np.sin(angle)
return np.array([
[1.0, 0.0, 0.0],
[0.0, c, -s],
[0.0, s, c],
])
def rot_y(angle):
c, s = np.cos(angle), np.sin(angle)
return np.array([
[ c, 0.0, s],
[0.0, 1.0, 0.0],
[-s, 0.0, c],
])
def rot_z(angle):
c, s = np.cos(angle), np.sin(angle)
return np.array([
[ c, -s, 0.0],
[ s, c, 0.0],
[0.0, 0.0, 1.0],
])
# Wireframe-домик. Origin выбран внутри объекта.
HOUSE_POINTS = np.array([
[-0.8, -0.6, -0.6],
[ 0.8, -0.6, -0.6],
[ 0.8, 0.6, -0.6],
[-0.8, 0.6, -0.6],
[-0.8, -0.6, 0.35],
[ 0.8, -0.6, 0.35],
[ 0.8, 0.6, 0.35],
[-0.8, 0.6, 0.35],
[ 0.0, -0.6, 1.05],
[ 0.0, 0.6, 1.05],
], dtype=float)
HOUSE_EDGES = [
# нижний прямоугольник
(0, 1), (1, 2), (2, 3), (3, 0),
# стены
(0, 4), (1, 5), (2, 6), (3, 7),
# верх стен
(4, 5), (5, 6), (6, 7), (7, 4),
# крыша
(4, 8), (5, 8),
(7, 9), (6, 9),
(8, 9),
]
def matrix_diagnostics(M):
return {
"orth_error": np.linalg.norm(M.T @ M - np.eye(3)),
"det": np.linalg.det(M),
}
def add_frame(fig, origin, basis=np.eye(3), axis_length=0.65, row=1, col=1, prefix=""):
"""Рисует тройку локальных осей. Столбцы basis — направления осей."""
origin = np.asarray(origin, dtype=float)
for i, label in enumerate(["x", "y", "z"]):
endpoint = origin + axis_length * basis[:, i]
fig.add_trace(
go.Scatter3d(
x=[origin[0], endpoint[0]],
y=[origin[1], endpoint[1]],
z=[origin[2], endpoint[2]],
mode="lines+text",
text=["", f"{prefix}{label}"],
textposition="top center",
showlegend=False,
hoverinfo="skip",
),
row=row,
col=col,
)
def add_axis_through_origin(fig, axis, label, row=1, col=1, length=1.35):
"""Рисует прямую через origin в направлении axis."""
axis = np.asarray(axis, dtype=float)
axis = axis / np.linalg.norm(axis)
p1 = -length * axis
p2 = length * axis
fig.add_trace(
go.Scatter3d(
x=[p1[0], p2[0]],
y=[p1[1], p2[1]],
z=[p1[2], p2[2]],
mode="lines+text",
text=["", label],
textposition="top center",
showlegend=False,
hoverinfo="skip",
),
row=row,
col=col,
)
def house_segments(points):
"""Преобразует вершины домика в последовательность сегментов для Scatter3d."""
segments = []
for i, j in HOUSE_EDGES:
segments.extend([
points[i],
points[j],
[np.nan, np.nan, np.nan],
])
return np.asarray(segments, dtype=float)
def add_house(fig, M, row=1, col=1, draw_axis=True):
"""Применяет M к домику; draw_axis управляет отображением локальных осей объекта."""
# Вопрос: в формулах мы пишем x' = Mx. Почему здесь появляется M.T?
points = HOUSE_POINTS @ M.T
segments = house_segments(points)
fig.add_trace(
go.Scatter3d(
x=segments[:, 0],
y=segments[:, 1],
z=segments[:, 2],
mode="lines",
showlegend=False,
hoverinfo="skip",
),
row=row,
col=col,
)
fig.add_trace(
go.Scatter3d(
x=points[:, 0],
y=points[:, 1],
z=points[:, 2],
mode="markers",
marker=dict(size=3),
showlegend=False,
hoverinfo="skip",
),
row=row,
col=col,
)
# Тот же оператор действует и на локальный базис объекта.
if draw_axis:
add_frame(fig, np.zeros(3), M, row=row, col=col, prefix="o_")
def set_scene_equal(fig, scene_name, lim=1.7):
fig.layout[scene_name].update(
aspectmode="cube",
xaxis=dict(range=[-lim, lim], title="X_w"),
yaxis=dict(range=[-lim, lim], title="Y_w"),
zaxis=dict(range=[-lim, lim], title="Z_w"),
)
ANGLE_1 = np.radians(55)
ANGLE_2 = np.radians(75)
R1 = rot_z(ANGLE_1)
R2 = rot_x(ANGLE_2)
M_reflect = np.diag([1.0, 1.0, -1.0])
for name, M in [("R1", R1), ("R2", R2), ("Reflection M", M_reflect)]:
d = matrix_diagnostics(M)
print(
f"{name:12s} | "
f"||M^T M-I|| = {d['orth_error']:.6f} | "
f"det = {d['det']:.6f}"
)In [ ]:
transforms = [
("Исходный домик", np.eye(3)),
("R1: rotation", R1),
("R2: rotation", R2),
("M: reflection", M_reflect),
]
fig = make_subplots(
rows=2,
cols=2,
specs=[
[{"type": "scene"}, {"type": "scene"}],
[{"type": "scene"}, {"type": "scene"}],
],
subplot_titles=[title for title, _ in transforms],
)
scene_names = ["scene", "scene2", "scene3", "scene4"]
for idx, ((title, M), scene_name) in enumerate(zip(transforms, scene_names), start=1):
row = 1 if idx <= 2 else 2
col = 1 if idx % 2 == 1 else 2
add_house(fig, M, row=row, col=col)
set_scene_equal(fig, scene_name)
fig.update_layout(
width=1050,
height=850,
margin=dict(l=10, r=10, t=70, b=10),
)
fig.show()In [ ]:
A = 0.5 * (R1 + R2)
R_comp = R2 @ R1
for name, M in [("R1", R1), ("R2", R2), ("(R1+R2)/2", A), ("R2 @ R1", R_comp)]:
d = matrix_diagnostics(M)
print(
f"{name:12s} | "
f"||M^T M-I|| = {d['orth_error']:.6f} | "
f"det = {d['det']:.6f}"
)In [ ]:
variants = [
("Исходный домик", np.eye(3)),
("(R1+R2)/2: не rotation", A),
("R2 @ R1: композиция", R_comp),
]
fig = make_subplots(
rows=1,
cols=3,
specs=[[{"type": "scene"}, {"type": "scene"}, {"type": "scene"}]],
subplot_titles=[title for title, _ in variants],
)
for col, (title, M) in enumerate(variants, start=1):
add_house(fig, M, row=1, col=col)
for scene_name in ["scene", "scene2", "scene3"]:
set_scene_equal(fig, scene_name)
fig.update_layout(
width=1300,
height=460,
margin=dict(l=10, r=10, t=70, b=10),
)
fig.show()In [ ]:
(R2 @ R1), (R1 @ R2)In [ ]:
# Одни и те же углы для двух эквивалентных последовательностей.
yaw = np.radians(45)
pitch = np.radians(40)
roll = np.radians(30)
# intrinsic ZYX: moving/body axes -> right multiplication
Q_intrinsic = [
np.eye(3),
rot_z(yaw),
rot_z(yaw) @ rot_y(pitch),
rot_z(yaw) @ rot_y(pitch) @ rot_x(roll),
]
# extrinsic XYZ: fixed/world axes -> left multiplication
Q_extrinsic = [
np.eye(3),
rot_x(roll),
rot_y(pitch) @ rot_x(roll),
rot_z(yaw) @ rot_y(pitch) @ rot_x(roll),
]
titles_top = [
"initial",
"yaw about body z",
"pitch about body y′",
"roll about body x″",
]
titles_bottom = [
"initial",
"roll about world x",
"pitch about world y",
"yaw about world z",
]
fig = make_subplots(
rows=2,
cols=4,
specs=[
[{"type": "scene"}] * 4,
[{"type": "scene"}] * 4,
],
subplot_titles=titles_top + titles_bottom,
vertical_spacing=0.06,
)
# Верхний ряд: intrinsic ZYX.
for col, Q in enumerate(Q_intrinsic, start=1):
add_house(fig, Q, row=1, col=col)
# Неподвижный world frame — ориентир.
add_frame(
fig,
np.zeros(3),
np.eye(3),
axis_length=0.9,
row=1,
col=col,
prefix="w_",
)
# Нижний ряд: extrinsic XYZ.
for col, Q in enumerate(Q_extrinsic, start=1):
add_house(fig, Q, row=2, col=col)
add_frame(
fig,
np.zeros(3),
np.eye(3),
axis_length=0.9,
row=2,
col=col,
prefix="w_",
)
for i in range(1, 9):
scene_name = "scene" if i == 1 else f"scene{i}"
set_scene_equal(fig, scene_name, lim=1.65)
fig.update_layout(
width=1450,
height=780,
margin=dict(l=10, r=10, t=80, b=10),
)
fig.show()
print(
"Финальные матрицы совпадают:",
np.allclose(Q_intrinsic[-1], Q_extrinsic[-1]),
)
print(
"||Q_intrinsic - Q_extrinsic||_F =",
np.linalg.norm(Q_intrinsic[-1] - Q_extrinsic[-1]),
)In [ ]:
def R_zyx(yaw, pitch, roll):
"""Final orientation for intrinsic ZYX = extrinsic XYZ."""
return rot_z(yaw) @ rot_y(pitch) @ rot_x(roll)
# Hands-on: поменяйте три угла и посмотрите на ориентацию домика.
YAW_DEG = 80
PITCH_DEG = 25
ROLL_DEG = -20
R_euler = R_zyx(
np.radians(YAW_DEG),
np.radians(PITCH_DEG),
np.radians(ROLL_DEG),
)
fig = make_subplots(
rows=1,
cols=2,
specs=[[{"type": "scene"}, {"type": "scene"}]],
subplot_titles=[
"Исходная ориентация",
f"yaw={YAW_DEG}°, pitch={PITCH_DEG}°, roll={ROLL_DEG}°",
],
)
add_house(fig, np.eye(3), row=1, col=1)
add_house(fig, R_euler, row=1, col=2)
set_scene_equal(fig, "scene")
set_scene_equal(fig, "scene2")
fig.update_layout(width=1000, height=470, margin=dict(l=10, r=10, t=70, b=10))
fig.show()
print("R =")
print(R_euler)
print("\nR^T R =")
print(R_euler.T @ R_euler)
print("\ndet(R) =", np.linalg.det(R_euler))In [ ]:
def add_axis_line(fig, axis, label, row, col, length=1.2):
axis = np.asarray(axis, dtype=float)
axis = axis / np.linalg.norm(axis)
endpoint = length * axis
fig.add_trace(
go.Scatter3d(
x=[0.0, endpoint[0]], y=[0.0, endpoint[1]], z=[0.0, endpoint[2]],
mode="lines+text", text=["", label], textposition="top center",
showlegend=False, hoverinfo="skip",
),
row=row, col=col,
)
def gimbal_axes_zyx(yaw, pitch):
e_x = np.array([1.0, 0.0, 0.0])
e_y = np.array([0.0, 1.0, 0.0])
e_z = np.array([0.0, 0.0, 1.0])
yaw_axis = e_z
pitch_axis = rot_z(yaw) @ e_y
roll_axis = rot_z(yaw) @ rot_y(pitch) @ e_x
return yaw_axis, pitch_axis, roll_axis
YAW = np.radians(0)
ROLL = np.radians(30)
cases = [
("pitch = 30°", np.radians(30)),
("pitch = 90° — gimbal lock", np.radians(90)),
]
fig = make_subplots(
rows=1,
cols=2,
specs=[[{"type": "scene"}, {"type": "scene"}]],
subplot_titles=[title for title, _ in cases],
)
for col, (title, pitch) in enumerate(cases, start=1):
R = R_zyx(YAW, pitch, ROLL)
add_house(fig, R, row=1, col=col)
yaw_axis, pitch_axis, roll_axis = gimbal_axes_zyx(YAW, pitch)
add_axis_line(fig, yaw_axis, "yaw axis", 1, col)
add_axis_line(fig, pitch_axis, "pitch axis", 1, col)
add_axis_line(fig, roll_axis, "roll axis", 1, col)
print(f"{title:27s} | <yaw, roll> = {np.dot(yaw_axis, roll_axis): .6f}")
set_scene_equal(fig, "scene")
set_scene_equal(fig, "scene2")
fig.update_layout(width=1050, height=500, margin=dict(l=10, r=10, t=70, b=10))
fig.show()In [ ]:
pitch_lock = np.pi / 2
angle_sets = [
(0.2, pitch_lock, 0.0),
(0.0, pitch_lock, -0.2),
(0.7, pitch_lock, 0.5),
]
rotations = [R_zyx(*angles) for angles in angle_sets]
for i, angles in enumerate(angle_sets):
yaw, pitch, roll = angles
print(
f"set {i}: yaw={yaw:+.2f}, pitch={np.degrees(pitch):.1f}°, "
f"roll={roll:+.2f}, yaw-roll={yaw-roll:+.2f}"
)
print()
print("R0 == R1:", np.allclose(rotations[0], rotations[1], atol=1e-12))
print("R0 == R2:", np.allclose(rotations[0], rotations[2], atol=1e-12))In [ ]:
yaw0 = 0.4
roll0 = -0.3
eps = 1e-6
pitch_values = np.linspace(0.0, np.pi / 2, 300)
responses = []
for pitch in pitch_values:
R0 = R_zyx(yaw0, pitch, roll0)
R1_eps = R_zyx(yaw0 + eps, pitch, roll0 + eps)
responses.append(np.linalg.norm(R1_eps - R0, ord="fro") / eps)
responses = np.asarray(responses)
fig = go.Figure()
fig.add_trace(go.Scatter(x=np.degrees(pitch_values), y=responses, mode="lines", name="sensitivity"))
fig.update_layout(
title="Одно направление Euler-параметров становится невидимым",
xaxis_title="pitch θ, degrees",
yaxis_title="||ΔR||_F / ε",
width=850,
height=430,
)
fig.show()
for pitch_deg in [0, 60, 80, 89, 90]:
pitch = np.radians(pitch_deg)
R0 = R_zyx(yaw0, pitch, roll0)
R1_eps = R_zyx(yaw0 + eps, pitch, roll0 + eps)
response = np.linalg.norm(R1_eps - R0, ord="fro") / eps
print(f"pitch={pitch_deg:2d}° -> sensitivity={response:.8f}")In [ ]:
def quat_from_axis_angle(axis, angle):
"""Unit quaternion q=(w, x, y, z) from axis-angle."""
axis = np.asarray(axis, dtype=float)
axis = axis / np.linalg.norm(axis)
half = 0.5 * angle
return np.concatenate([
[np.cos(half)],
axis * np.sin(half),
])
def quat_to_R(q):
"""Rotation matrix from quaternion q=(w, x, y, z)."""
q = np.asarray(q, dtype=float)
q = q / np.linalg.norm(q)
w, x, y, z = q
return np.array([
[1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y)],
[2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x)],
[2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)],
])
def quat_mul(q1, q2):
"""Hamilton product q1 ⊗ q2, quaternion format: (w, x, y, z)."""
q1 = np.asarray(q1, dtype=float)
q2 = np.asarray(q2, dtype=float)
w1, v1 = q1[0], q1[1:]
w2, v2 = q2[0], q2[1:]
return np.concatenate([
[w1 * w2 - np.dot(v1, v2)],
w1 * v2 + w2 * v1 + np.cross(v1, v2),
])
In [ ]:
axis = np.array([1.0, 1.0, 1.0])
axis = axis / np.linalg.norm(axis)
angle = np.radians(45)
q = quat_from_axis_angle(axis, angle)
R_q = quat_to_R(q)
R_minus_q = quat_to_R(-q)
print("axis u =", axis)
print("angle θ =", np.degrees(angle), "degrees")
print("q =", q)
print("-q =", -q)
print("||q|| =", np.linalg.norm(q))
print("R(q) == R(-q):", np.allclose(R_q, R_minus_q))
print("det R(q) =", np.linalg.det(R_q))
fig = make_subplots(
rows=1,
cols=3,
specs=[[{"type": "scene"}, {"type": "scene"}, {"type": "scene"}]],
subplot_titles=["initial house", "rotation from q", "rotation from -q"],
)
# Initial orientation
add_house(fig, np.eye(3), row=1, col=1)
add_frame(fig, np.zeros(3), np.eye(3), axis_length=0.9, row=1, col=1, prefix="w_")
add_axis_through_origin(fig, axis, "axis u", row=1, col=1)
# Quaternion q
add_house(fig, R_q, row=1, col=2)
add_frame(fig, np.zeros(3), np.eye(3), axis_length=0.9, row=1, col=2, prefix="w_")
add_axis_through_origin(fig, axis, "axis u", row=1, col=2)
# Quaternion -q
add_house(fig, R_minus_q, row=1, col=3)
add_frame(fig, np.zeros(3), np.eye(3), axis_length=0.9, row=1, col=3, prefix="w_")
add_axis_through_origin(fig, axis, "axis u", row=1, col=3)
set_scene_equal(fig, "scene")
set_scene_equal(fig, "scene2")
set_scene_equal(fig, "scene3")
fig.update_layout(
width=1350,
height=470,
margin=dict(l=10, r=10, t=60, b=10),
)
fig.show()In [ ]:
from scipy.spatial.transform import Rotation
q1 = quat_from_axis_angle([1,0,0], np.radians(45))
q2 = quat_from_axis_angle([1,0,0], np.radians(15))
rot_comp = Rotation.from_quat(np.roll(q2, -1)) * Rotation.from_quat(np.roll(q1, -1))
np.allclose(rot_comp.as_matrix(), rot_x(np.radians(60)))In [ ]:
# Наивный additive update в R^4 уже не обязан оставаться unit quaternion.
delta_q = np.array([0.00, 0.04, -0.03, 0.02])
q_raw = q + delta_q
q_projected = q_raw / np.linalg.norm(q_raw)
print("||q|| =", np.linalg.norm(q))
print("||q + delta_q|| =", np.linalg.norm(q_raw))
print("||normalize(q+delta)|| =", np.linalg.norm(q_projected))In [ ]:
def slerp(q0, q1, t):
"""Shortest-path SLERP, quaternion format: (w, x, y, z)."""
q0 = np.asarray(q0, dtype=float)
q1 = np.asarray(q1, dtype=float)
q0 = q0 / np.linalg.norm(q0)
q1 = q1 / np.linalg.norm(q1)
dot = float(np.clip(np.dot(q0, q1), -1.0, 1.0))
if dot < 0.0:
q1 = -q1
dot = -dot
if dot > 0.9995:
q = (1.0 - t) * q0 + t * q1
return q / np.linalg.norm(q)
omega = np.arccos(dot)
sin_omega = np.sin(omega)
return (
np.sin((1.0 - t) * omega) / sin_omega * q0
+ np.sin(t * omega) / sin_omega * q1
)
q0 = quat_from_axis_angle([0.0, 0.0, 1.0], np.radians(-20.0))
q1 = quat_from_axis_angle([1.0, 1.0, 0.4], np.radians(135.0))
t0 = np.array([-2.6, -1.0, 0.0])
t1 = np.array([ 2.6, 1.0, 0.8])
ts = np.linspace(0.0, 1.0, 7)
origins = np.array([(1.0 - t) * t0 + t * t1 for t in ts])
fig = go.Figure()
fig.add_trace(go.Scatter3d(
x=origins[:, 0],
y=origins[:, 1],
z=origins[:, 2],
mode="lines+markers",
name="pose origin trajectory",
))
house_scale = 0.38
for t in ts:
q_t = slerp(q0, q1, float(t))
R_t = quat_to_R(q_t)
c_t = (1.0 - t) * t0 + t * t1
points_t = (house_scale * HOUSE_POINTS) @ R_t.T + c_t
segments_t = house_segments(points_t)
fig.add_trace(go.Scatter3d(
x=segments_t[:, 0],
y=segments_t[:, 1],
z=segments_t[:, 2],
mode="lines",
name=f"t={t:.2f}",
showlegend=False,
opacity=0.65,
))
fig.update_layout(
title="SLERP rotation + linear translation between two poses",
width=950,
height=520,
margin=dict(l=10, r=10, t=60, b=10),
scene=dict(
aspectmode="data",
xaxis_title="x",
yaxis_title="y",
zaxis_title="z",
),
)
fig.show()
In [ ]:
def hat(omega):
"""R^3 -> so(3)."""
wx, wy, wz = np.asarray(omega, dtype=float)
return np.array([
[0.0, -wz, wy],
[wz, 0.0, -wx],
[-wy, wx, 0.0],
])
def vee(Omega):
"""so(3) -> R^3, inverse operation for hat()."""
Omega = np.asarray(Omega, dtype=float)
return np.array([
Omega[2, 1],
Omega[0, 2],
Omega[1, 0],
])
omega = np.array([0.3, -0.2, 0.5])
Omega = hat(omega)
x = np.array([0.7, 0.4, -0.1])
print("omega =", omega)
print("hat(omega) =")
print(Omega)
print()
print("||Omega^T + Omega|| =", np.linalg.norm(Omega.T + Omega))
print("hat(omega) @ x =", Omega @ x)
print("omega x x =", np.cross(omega, x))
print("vee(hat(omega)) =", vee(Omega))In [ ]:
(Omega @ Omega.T)In [ ]:
# Посмотрим на цикличность степеней U = hat(u) на конкретной оси.
omega = np.array([1.0, 0.7, 0.35])
theta = np.linalg.norm(omega)
u = omega / theta
U = hat(u)
U2 = U @ U
U3 = U2 @ U
U4 = U3 @ U
U5 = U4 @ U
print("u =", u)
print()
print("||U^3 + U|| =", np.linalg.norm(U3 + U))
print("||U^4 + U^2|| =", np.linalg.norm(U4 + U2))
print("||U^5 - U|| =", np.linalg.norm(U5 - U))
print()
print("Проверка U^2 = u u^T - I:")
print("||U^2 - (u u^T - I)|| =",
np.linalg.norm(U2 - (np.outer(u, u) - np.eye(3))))In [ ]:
def exp_so3(omega):
"""Exponential map R^3 -> SO(3), evaluated with Rodrigues formula."""
omega = np.asarray(omega, dtype=float)
theta = np.linalg.norm(omega)
Omega = hat(omega)
if theta < 1e-8:
# Первые члены exp(Omega); достаточно для численно малого theta.
return np.eye(3) + Omega + 0.5 * (Omega @ Omega)
A = np.sin(theta) / theta
B = (1.0 - np.cos(theta)) / (theta * theta)
return np.eye(3) + A * Omega + B * (Omega @ Omega)
axis = np.array([1.0, 0.7, 0.35])
axis = axis / np.linalg.norm(axis)
theta = np.radians(50)
omega_demo = theta * axis
Omega_demo = hat(omega_demo)
M_linear = np.eye(3) + Omega_demo
R_exact = exp_so3(omega_demo)
print("step angle =", np.degrees(theta), "degrees")
print()
print("I + hat(omega):")
print(" ||M^T M - I|| =", matrix_diagnostics(M_linear)["orth_error"])
print(" det(M) =", matrix_diagnostics(M_linear)["det"])
print()
print("exp(hat(omega)):")
print(" ||R^T R - I|| =", matrix_diagnostics(R_exact)["orth_error"])
print(" det(R) =", matrix_diagnostics(R_exact)["det"])
fig = make_subplots(
rows=1,
cols=3,
specs=[[{"type": "scene"}, {"type": "scene"}, {"type": "scene"}]],
subplot_titles=[
"initial",
"tangent approximation: I + Ω",
"exact: Exp(Ω)",
],
)
add_house(fig, np.eye(3), row=1, col=1)
add_house(fig, M_linear, row=1, col=2)
add_house(fig, R_exact, row=1, col=3)
for col in (1, 2, 3):
add_axis_through_origin(fig, axis, "axis u", row=1, col=col)
set_scene_equal(fig, "scene")
set_scene_equal(fig, "scene2")
set_scene_equal(fig, "scene3")
fig.update_layout(
width=1350,
height=470,
margin=dict(l=10, r=10, t=70, b=10),
)
fig.show()In [ ]:
# Текущая ориентация уже далеко от identity.
R_old = rot_z(np.radians(55)) @ rot_y(np.radians(-25))
# Это НЕ три Euler angles.
# Это один локальный rotation vector в body coordinates.
delta_omega_body = np.array([0.12, -0.05, 0.08])
R_new = R_old @ exp_so3(delta_omega_body)
# Ось body increment, выраженная в world coordinates.
delta_axis_body = delta_omega_body / np.linalg.norm(delta_omega_body)
delta_axis_world = R_old @ delta_axis_body
fig = make_subplots(
rows=1,
cols=2,
specs=[[{"type": "scene"}, {"type": "scene"}]],
subplot_titles=[
"current state R_old",
"after local update R_old Exp(δω^)",
],
)
add_house(fig, R_old, row=1, col=1)
add_house(fig, R_new, row=1, col=2)
add_axis_through_origin(
fig, delta_axis_world, "local update axis", row=1, col=1
)
add_axis_through_origin(
fig, delta_axis_world, "local update axis", row=1, col=2
)
set_scene_equal(fig, "scene")
set_scene_equal(fig, "scene2")
fig.update_layout(
width=950,
height=470,
margin=dict(l=10, r=10, t=70, b=10),
)
fig.show()
print("R_old: ||R^T R-I|| =", matrix_diagnostics(R_old)["orth_error"])
print("R_new: ||R^T R-I|| =", matrix_diagnostics(R_new)["orth_error"])
print("R_new: det(R) =", matrix_diagnostics(R_new)["det"])In [ ]:
def make_T(R, t):
"""Собирает homogeneous rigid transform T in SE(3)."""
T = np.eye(4)
T[:3, :3] = np.asarray(R, dtype=float)
T[:3, 3] = np.asarray(t, dtype=float)
return T
def inv_T(T):
"""Inverse of a rigid transform."""
R = T[:3, :3]
t = T[:3, 3]
T_inv = np.eye(4)
T_inv[:3, :3] = R.T
T_inv[:3, 3] = -R.T @ t
return T_inv
def R_t_from_T(T):
"""Вытащить компоненты rotation и translation из T in SE(3)."""
return T[:3, :3], T[:3, 3]
def add_house_pose(fig, T, row=1, col=1, draw_axis=True):
"""Рисует домик после SE(3)-преобразования."""
R, t = R_t_from_T(T)
points = (R @ HOUSE_POINTS.T).T + t
segments = house_segments(points)
fig.add_trace(
go.Scatter3d(
x=segments[:, 0], y=segments[:, 1], z=segments[:, 2],
mode="lines", showlegend=False, hoverinfo="skip",
), row=row, col=col,
)
fig.add_trace(
go.Scatter3d(
x=points[:, 0], y=points[:, 1], z=points[:, 2],
mode="markers", marker=dict(size=3), showlegend=False, hoverinfo="skip",
), row=row, col=col,
)
if draw_axis:
add_frame(fig, t, R, row=row, col=col, prefix="o_")
def add_translation_vector(fig, t, row=1, col=1, label="t"):
"""Радиус-вектор от world origin до origin преобразованного body frame."""
t = np.asarray(t, dtype=float)
if np.linalg.norm(t) < 1e-12:
return
fig.add_trace(
go.Scatter3d(
x=[0.0, t[0]], y=[0.0, t[1]], z=[0.0, t[2]],
mode="lines+markers+text",
text=["", label], textposition="top center",
marker=dict(size=[2, 5]), showlegend=False, hoverinfo="skip",
), row=row, col=col,
)
R_demo = rot_z(np.radians(60))
t_demo = np.array([0.75, 0.25, 0.35])
T_rot = make_T(R_demo, np.zeros(3))
T_shift = make_T(np.eye(3), t_demo)
# Верхняя строка: сначала rotation, затем translation.
T_shift_after_rot = T_shift @ T_rot
# Нижняя строка: сначала translation, затем rotation around world origin.
T_rot_after_shift = T_rot @ T_shift
fig = make_subplots(
rows=2, cols=3,
specs=[
[{"type": "scene"}, {"type": "scene"}, {"type": "scene"}],
[{"type": "scene"}, {"type": "scene"}, {"type": "scene"}],
],
subplot_titles=[
"initial", "1) rotate", "2) then translate",
"initial", "1) translate", "2) then rotate",
],
vertical_spacing=0.06,
)
top_sequence = [np.eye(4), T_rot, T_shift_after_rot]
bottom_sequence = [np.eye(4), T_shift, T_rot_after_shift]
for col, T in enumerate(top_sequence, start=1):
add_house_pose(fig, T, row=1, col=col)
_, t = R_t_from_T(T)
add_translation_vector(fig, t, row=1, col=col, label="t")
for col, T in enumerate(bottom_sequence, start=1):
add_house_pose(fig, T, row=2, col=col)
_, t = R_t_from_T(T)
add_translation_vector(fig, t, row=2, col=col, label="t")
for i in range(1, 7):
scene_name = "scene" if i == 1 else f"scene{i}"
set_scene_equal(fig, scene_name, lim=2.1)
fig.update_layout(width=1350, height=850, margin=dict(l=10, r=10, t=80, b=10))
fig.show()
R_rot_after_shift, t_rot_after_shift = R_t_from_T(T_rot_after_shift)
R_shift_after_rot, t_shift_after_rot = R_t_from_T(T_shift_after_rot)
print("Проверяем rotation-компонент обеих композиций:")
print(" R(translate → rotate) == R_demo:", np.allclose(R_rot_after_shift, R_demo))
print(" R(rotate → translate) == R_demo:", np.allclose(R_shift_after_rot, R_demo))
print("\nПроверяем translation-компонент:")
print(" t(rotate → translate) == t_demo:", np.allclose(t_shift_after_rot, t_demo))
print(" t(translate → rotate) == t_demo:", np.allclose(t_rot_after_shift, t_demo))
print(" t(translate → rotate) == R_demo @ t_demo:", np.allclose(t_rot_after_shift, R_demo @ t_demo))
print("\nПочему?")
print(" t_demo =", np.round(t_demo, 4))
print(" R_demo @ t_demo =", np.round(R_demo @ t_demo, 4))
print(" actual final t =", np.round(t_rot_after_shift, 4))
print("\nПроверка inverse:")
print(" ||T T^{-1} - I|| =", np.linalg.norm(T_shift_after_rot @ inv_T(T_shift_after_rot) - np.eye(4)))In [ ]:
def hat_se3(xi):
"""R^6 -> se(3), convention xi = [rho, omega]."""
xi = np.asarray(xi, dtype=float)
rho = xi[:3]
omega = xi[3:]
Xi = np.zeros((4, 4))
Xi[:3, :3] = hat(omega)
Xi[:3, 3] = rho
return Xi
xi_demo = np.array([
0.8, 0.15, 0.25, # rho
0.0, 0.0, 0.9, # omega
])
Xi = hat_se3(xi_demo)
print("xi = [rho, omega] =", xi_demo)
print()
print("xi^ =")
print(Xi)
print()
print("rotation block is skew:")
print("||Omega^T + Omega|| =",
np.linalg.norm(Xi[:3, :3].T + Xi[:3, :3]))In [ ]:
_R, _t = R_t_from_T(Xi)
(_R == -_R.T).all()In [ ]:
def V_so3(omega):
"""Translation coupling matrix in SE(3) exponential."""
omega = np.asarray(omega, dtype=float)
theta = np.linalg.norm(omega)
Omega = hat(omega)
if theta < 1e-8:
return (
np.eye(3)
+ 0.5 * Omega
+ (1.0 / 6.0) * (Omega @ Omega)
)
B = (1.0 - np.cos(theta)) / (theta * theta)
C = (theta - np.sin(theta)) / (theta**3)
return np.eye(3) + B * Omega + C * (Omega @ Omega)
def exp_se3(xi):
"""Exponential map R^6 -> SE(3), convention xi=[rho, omega]."""
xi = np.asarray(xi, dtype=float)
rho = xi[:3]
omega = xi[3:]
R = exp_so3(omega)
t = V_so3(omega) @ rho
return make_T(R, t)
# Один constant twist: simultaneous translation + rotation.
xi = np.array([
1.20, 0.15, 0.35, # rho
0.10, -0.05, 1.00, # omega
])
samples = np.linspace(0.0, 1.0, 7)
Ts = [exp_se3(s * xi) for s in samples]
origins = np.array([T[:3, 3] for T in Ts])
fig = make_subplots(rows=1, cols=1, specs=[[{"type": "scene"}]])
# Несколько промежуточных положений тела.
for i, T in enumerate(Ts):
# Оси показываем только в начале и конце, иначе рисунок перегружается.
draw_axis = i in (0, len(Ts) - 1)
R = T[:3, :3]
t = T[:3, 3]
points = (R @ HOUSE_POINTS.T).T + t
segments = house_segments(points)
fig.add_trace(
go.Scatter3d(
x=segments[:, 0],
y=segments[:, 1],
z=segments[:, 2],
mode="lines",
showlegend=False,
hoverinfo="skip",
)
)
if draw_axis:
add_frame(fig, t, R, prefix="o_" if i else "start_")
# Траектория origin body frame.
fig.add_trace(
go.Scatter3d(
x=origins[:, 0],
y=origins[:, 1],
z=origins[:, 2],
mode="lines+markers",
name="body origin trajectory",
)
)
fig.update_layout(
width=900,
height=600,
margin=dict(l=10, r=10, t=50, b=10),
scene=dict(
aspectmode="cube",
xaxis=dict(range=[-1.5, 2.2], title="X_w"),
yaxis=dict(range=[-1.5, 2.2], title="Y_w"),
zaxis=dict(range=[-1.5, 2.2], title="Z_w"),
),
)
fig.show()
T_final = Ts[-1]
rho = xi[:3]
print("rho =", rho)
print("final translation t =", T_final[:3, 3])
print("||t - rho|| =", np.linalg.norm(T_final[:3, 3] - rho))
print()
print("final rotation diagnostics:")
print("||R^T R-I|| =", matrix_diagnostics(T_final[:3, :3])["orth_error"])
print("det R =", matrix_diagnostics(T_final[:3, :3])["det"])In [ ]:
yaw, pitch, roll = np.radians([30.0, 40.0, -20.0])
R0 = R_zyx(yaw, pitch, roll)
eps = 1e-7
dR_dyaw = (
R_zyx(yaw + eps, pitch, roll) - R0
) / eps
delta_yaw = np.radians(15.0)
# 1) Taylor approximation treated as a finite new matrix.
R_linear = R0 + delta_yaw * dR_dyaw
# 2) Correct Euler-parameter update: rebuild R from new angles.
R_euler_exact = R_zyx(yaw + delta_yaw, pitch, roll)
# 3) The same world-z update through the exponential map.
R_lie = exp_so3(np.array([0.0, 0.0, delta_yaw])) @ R0
def print_rotation_check(name, R):
diag = matrix_diagnostics(R)
print(
f"{name:22s} | "
f"||R^T R-I|| = {diag['orth_error']:.6e} | "
f"det(R) = {diag['det']:.8f}"
)
print_rotation_check("initial R", R0)
print_rotation_check("linearized update", R_linear)
print_rotation_check("exact Euler update", R_euler_exact)
print_rotation_check("Lie Exp update", R_lie)
print()
print(
"Exact Euler and Lie update coincide:",
np.allclose(R_euler_exact, R_lie, atol=1e-8),
)In [ ]:
# Служебный код для 3D–3D alignment.
# Внутренности finite-difference Jacobian можно не разбирать построчно.
def transform_points(T, X):
R, t = R_t_from_T(T)
return (R @ X.T).T + t
def alignment_residual(T, X, Y):
return (transform_points(T, X) - Y).reshape(-1)
def numerical_pose_jacobian(T, X, Y, eps=1e-6):
r0 = alignment_residual(T, X, Y)
J = np.zeros((r0.size, 6))
for j in range(6):
delta = np.zeros(6)
delta[j] = eps
T_perturbed = T @ exp_se3(delta)
r_perturbed = alignment_residual(T_perturbed, X, Y)
J[:, j] = (r_perturbed - r0) / eps
return r0, J
def gauss_newton_pose(T0, X, Y, n_iter=8, damping=1e-8):
T = T0.copy()
cost_trace = []
for _ in range(n_iter):
r, J = numerical_pose_jacobian(T, X, Y)
# Scalar objective value L(T_k) = 0.5 * ||r(T_k)||^2.
cost_trace.append(0.5 * r @ r)
# damping=0 -> pure Gauss-Newton.
# Tiny positive damping stabilizes an ill-conditioned normal matrix.
H = J.T @ J + damping * np.eye(6)
g = J.T @ r
delta = np.linalg.solve(H, -g)
# Ключевая строка: local Euclidean step -> new pose on SE(3).
T = T @ exp_se3(delta)
r_final = alignment_residual(T, X, Y)
cost_trace.append(0.5 * r_final @ r_final)
return T, np.asarray(cost_trace)In [ ]:
# Synthetic target pose.
X = HOUSE_POINTS.copy()
R_true = (
rot_z(np.radians(35))
@ rot_y(np.radians(-20))
@ rot_x(np.radians(12))
)
t_true = np.array([0.70, -0.45, 0.30])
T_true = make_T(R_true, t_true)
Y = transform_points(T_true, X)
# Намеренно неточная initial estimate.
R_init = (
rot_z(np.radians(-15))
@ rot_y(np.radians(10))
)
t_init = np.array([-0.30, 0.20, -0.10])
T_init = make_T(R_init, t_init)
T_est, cost_trace = gauss_newton_pose(
T_init,
X,
Y,
n_iter=8,
)
# --- Visualization: before / after / cost trace ---
fig = make_subplots(
rows=1,
cols=3,
specs=[[
{"type": "scene"},
{"type": "scene"},
{"type": "xy"},
]],
subplot_titles=[
"initial estimate vs target",
"after local SE(3) optimization",
"Gauss–Newton cost",
],
column_widths=[0.38, 0.38, 0.24],
)
# Initial estimate + target
add_house_pose(fig, T_init, row=1, col=1, draw_axis=True)
add_house_pose(fig, T_true, row=1, col=1, draw_axis=False)
# Final estimate + target
add_house_pose(fig, T_est, row=1, col=2, draw_axis=True)
add_house_pose(fig, T_true, row=1, col=2, draw_axis=False)
# Cost trace
fig.add_trace(
go.Scatter(
x=np.arange(len(cost_trace)),
y=cost_trace,
mode="lines+markers",
name="cost",
showlegend=False,
),
row=1,
col=3,
)
set_scene_equal(fig, "scene", lim=2.2)
set_scene_equal(fig, "scene2", lim=2.2)
fig.update_xaxes(title_text="iteration", row=1, col=3)
fig.update_yaxes(
title_text="0.5 ||r||²",
type="log",
row=1,
col=3,
)
fig.update_layout(
width=1450,
height=500,
margin=dict(l=10, r=10, t=70, b=10),
)
fig.show()
R_est, t_est = R_t_from_T(T_est)
R_error = R_est.T @ R_true
angle_error = np.arccos(
np.clip((np.trace(R_error) - 1.0) / 2.0, -1.0, 1.0)
)
translation_error = np.linalg.norm(t_est - t_true)
print("initial cost =", cost_trace[0])
print("final cost =", cost_trace[-1])
print(
"rotation error [deg] =",
np.degrees(angle_error),
)
print(
"translation error =",
translation_error,
)
