-
Notifications
You must be signed in to change notification settings - Fork 18
/
nano_pgo.py
1696 lines (1341 loc) · 62.4 KB
/
nano_pgo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import shutil
import importlib.util
import os
import time
import numpy as np
np.set_printoptions(linewidth=np.inf, suppress=True, precision=4)
from scipy.spatial.transform import Rotation
import scipy.sparse as sp
import sksparse.cholmod as cholmod
import sym
import symforce
symforce.set_epsilon_to_number()
import symforce.symbolic as sf
from symforce.ops import LieGroupOps
from symforce import codegen
from symforce.values import Values
from symforce.codegen import codegen_util
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import multiprocessing
import time
import functools
def timeit(func):
TIMEIT_ENABLED = False
@functools.wraps(func)
def wrapper_timeit(*args, **kwargs):
if TIMEIT_ENABLED:
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"[{func.__name__}] Time cost: {elapsed_time:.6f} sec.")
return result
else:
return func(*args, **kwargs)
return wrapper_timeit
def quat_to_rotmat(qx, qy, qz, qw):
rotation = Rotation.from_quat([qx, qy, qz, qw])
return rotation.as_matrix()
def rotvec_to_quat(rotvec):
rotation = Rotation.from_rotvec(rotvec)
q = rotation.as_quat()
return q
def rotmat_to_rotvec(R):
rotation = Rotation.from_matrix(R)
rotvec = rotation.as_rotvec()
return rotvec
def rotvec_to_rotmat(rotvec):
rotation = Rotation.from_rotvec(rotvec)
R = rotation.as_matrix()
return R
def skew_symmetric(v):
return np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
def se2_to_se3(x, y, theta):
rotation = Rotation.from_euler("z", theta)
R = rotation.as_matrix()
t = np.array([x, y, 0.0])
return R, t
def plot_two_poses_with_edges_plotly(
initial_poses_list,
optimized_poses_list,
edges,
iteration_name="",
skip=1,
):
"""
Visualizes initial and optimized poses along with edges using Plotly with equal axis scaling.
Parameters:
initial_poses_list (list of np.ndarray): List of initial pose translations (3D positions).
optimized_poses_list (list of np.ndarray): List of optimized pose translations (3D positions).
edges (list of dict): List of edges, where each edge contains "i", "j" for the indices.
skip (int, optional): Plot every 'skip' poses (default is 1, which plots all poses).
"""
# Prepare poses for plotting
initial_poses_np = np.array(
[pose for idx, pose in enumerate(initial_poses_list) if idx % skip == 0]
)
optimized_poses_np = np.array(
[pose for idx, pose in enumerate(optimized_poses_list) if idx % skip == 0]
)
# Create a scatter plot for initial and optimized poses
trace_initial = go.Scatter3d(
x=initial_poses_np[:, 0],
y=initial_poses_np[:, 1],
z=initial_poses_np[:, 2],
mode="markers",
marker=dict(size=5, color="red"),
name="Initial Poses",
)
trace_optimized = go.Scatter3d(
x=optimized_poses_np[:, 0],
y=optimized_poses_np[:, 1],
z=optimized_poses_np[:, 2],
mode="markers",
marker=dict(size=5, color="green"),
name="Optimized Poses",
)
# Create lines for edges
edge_traces = []
for edge in edges:
from_idx = edge["i"]
to_idx = edge["j"]
if from_idx < len(optimized_poses_list) and to_idx < len(optimized_poses_list):
# Extract positions for the line
x_vals = [
optimized_poses_list[from_idx][0],
optimized_poses_list[to_idx][0],
]
y_vals = [
optimized_poses_list[from_idx][1],
optimized_poses_list[to_idx][1],
]
z_vals = [
optimized_poses_list[from_idx][2],
optimized_poses_list[to_idx][2],
]
edge_trace = go.Scatter3d(
x=x_vals,
y=y_vals,
z=z_vals,
mode="lines",
line=dict(color="blue", width=2),
showlegend=False, # Don't show edges in the legend
)
edge_traces.append(edge_trace)
# Combine all poses to calculate axis ranges
all_points = np.vstack((initial_poses_np, optimized_poses_np))
x_range = [all_points[:, 0].min(), all_points[:, 0].max()]
y_range = [all_points[:, 1].min(), all_points[:, 1].max()]
z_range = [all_points[:, 2].min(), all_points[:, 2].max()]
# Calculate the overall range for equal axes
max_range = max(
x_range[1] - x_range[0], y_range[1] - y_range[0], z_range[1] - z_range[0]
)
x_mid = np.mean(x_range)
y_mid = np.mean(y_range)
z_mid = np.mean(z_range)
# Set new ranges to make axes equal
x_range = [x_mid - max_range / 2, x_mid + max_range / 2]
y_range = [y_mid - max_range / 2, y_mid + max_range / 2]
z_range = [z_mid - max_range / 2, z_mid + max_range / 2]
# Combine all traces
fig = go.Figure(data=[trace_initial, trace_optimized] + edge_traces)
# Update layout with equal axis scaling
fig.update_layout(
title=f"{iteration_name}: Initial and Optimized Poses with Edges (Equal Axes)",
scene=dict(
xaxis=dict(title="X", range=x_range),
yaxis=dict(title="Y", range=y_range),
zaxis=dict(title="Z", range=z_range),
aspectmode="cube", # Ensures the aspect ratio is equal for all axes
),
showlegend=True,
width=1200,
height=800,
)
# Show the plot
fig.show()
def plot_two_poses_with_edges_open3d(
initial_poses_list, optimized_poses_list, edges, skip=1
):
"""
Visualizes initial and optimized poses along with edges using Open3D.
Parameters:
initial_poses_list (list of np.ndarray): List of initial pose translations (3D positions).
optimized_poses_list (list of np.ndarray): List of optimized pose translations (3D positions).
edges (list of dict): List of edges, where each edge contains "i", "j" for the indices.
skip (int, optional): Plot every 'skip' poses (default is 1, which plots all poses).
"""
import open3d as o3d
def poses_to_point_cloud(pose_list, color, skip=1):
points = [pose for idx, pose in enumerate(pose_list) if idx % skip == 0]
points_np = np.array(points)
# Create Open3D point cloud
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points_np)
# Set point colors
colors_np = np.tile(color, (points_np.shape[0], 1))
pcd.colors = o3d.utility.Vector3dVector(colors_np)
return pcd
# Create two point clouds with different colors
pcd_initial = poses_to_point_cloud(
initial_poses_list, color=[1, 0, 0], skip=skip
) # Red for initial poses
pcd_optimized = poses_to_point_cloud(
optimized_poses_list, color=[0, 1, 0], skip=skip
) # Green for optimized poses
# Create lines for edges between poses
lines = []
line_colors = []
for edge in edges:
from_idx = edge["i"]
to_idx = edge["j"]
# Only plot edges if indices are valid
if from_idx < len(optimized_poses_list) and to_idx < len(optimized_poses_list):
# Line connects the from and to poses
line = [from_idx, to_idx]
lines.append(line)
line_colors.append([0, 0, 1]) # Blue color for the lines
# Create Open3D LineSet for the edges
if lines:
# Creates a LineSet object to represent edges between poses.
# Use the points from the optimized poses as vertices
line_set = o3d.geometry.LineSet()
points = np.array(optimized_poses_list)
line_set.points = o3d.utility.Vector3dVector(points)
line_set.lines = o3d.utility.Vector2iVector(lines)
line_set.colors = o3d.utility.Vector3dVector(line_colors)
else:
line_set = None
# Visualize both point clouds, lines, and axes
geometries = [pcd_initial, pcd_optimized]
if line_set:
geometries.append(line_set)
o3d.visualization.draw_geometries(
geometries,
zoom=0.8,
front=[0, 0, 1], # top view
lookat=initial_poses_list[-1],
up=[0, 1, 0],
)
#
# TODO: make these non-global (but must be called "once")
#
epsilon = 1e-7
# Define rotation variables (rotation vectors for each axis)
sf_ri = sf.V3.symbolic("ri") # Rotation of pose_i
sf_rj = sf.V3.symbolic("rj") # Rotation of pose_j
sf_rij = sf.V3.symbolic("rij") # Measured relative rotation
# Define translation variables
sf_ti = sf.V3.symbolic("ti") # Translation of pose_i
sf_tj = sf.V3.symbolic("tj") # Translation of pose_j
sf_tij = sf.V3.symbolic("tij") # Measured relative translation
# Create rotation matrices using Lie Group operations
sf_Ri = LieGroupOps.from_tangent(sf.Rot3, sf_ri)
sf_Rj = LieGroupOps.from_tangent(sf.Rot3, sf_rj)
sf_Rij = LieGroupOps.from_tangent(sf.Rot3, sf_rij)
# Construct SE(3) containers
sf_Ti = sf.Pose3(R=sf_Ri, t=sf_ti)
sf_Tj = sf.Pose3(R=sf_Rj, t=sf_tj)
sf_Tij = sf.Pose3(R=sf_Rij, t=sf_tij)
# SE3 error: T_err = T_ij^{-1} * T_i^{-1} * T_j
sf_T_err = sf_Tij.inverse() * (sf_Ti.inverse() * sf_Tj)
# Convert SE3 error to a tangent vector [r, t], 6-dim.
# NOTE: symforce uses the [r, t] order, not [t, r].
sf_se3_err = sf.Matrix(sf_T_err.to_tangent())
# Define residual as the rotation and translation error
sf_residual = sf_se3_err # 6D vector
# Compute the full Jacobian
sf_J_ti = sf_residual.jacobian([sf_ti]) # 6 x 3
sf_J_ri = sf_residual.jacobian([sf_ri]) # 6 x 3
sf_J_tj = sf_residual.jacobian([sf_tj]) # 6 x 3
sf_J_rj = sf_residual.jacobian([sf_rj]) # 6 x 3
def generate_compiled_between_error_func():
def sf_between_error(Ti: sf.Pose3, Tj: sf.Pose3, Tij: sf.Pose3):
return Tij.inverse() * (Ti.inverse() * Tj)
between_error_codegen = codegen.Codegen.function(
func=sf_between_error,
config=codegen.PythonConfig(),
)
between_error_codegen_with_jacobians = between_error_codegen.with_jacobians(
which_args=["Ti", "Tj"],
include_results=True,
)
between_error_codegen_with_jacobians_data = (
between_error_codegen_with_jacobians.generate_function()
)
import importlib.util
for file_path in between_error_codegen_with_jacobians_data.generated_files:
if file_path.name == "sf_between_error_with_jacobians01.py":
target_file = str(file_path)
break
else:
raise FileNotFoundError(
"sf_between_error_with_jacobians01.py not found in generated files."
)
spec = importlib.util.spec_from_file_location(
"sf_between_error_with_jacobians01", target_file
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return getattr(module, "sf_between_error_with_jacobians01")
sf_between_error_with_jacobians_func = generate_compiled_between_error_func()
@timeit
def between_factor_jacobian_by_symforce(pose_i, pose_j, pose_ij_meas):
"""
Computes the Jacobians for the between factor residual using Symforce symbolic computation.
Parameters:
pose_i (dict): Dictionary containing rotation vector 'r' and translation 't' for pose i.
pose_j (dict): Dictionary containing rotation vector 'r' and translation 't' for pose j.
pose_ij_meas (dict): Dictionary containing the measured relative rotation matrix 'R' and translation vector 't'.
Returns:
Ji (np.ndarray): 6x6 Jacobian matrix with respect to pose i.
Jj (np.ndarray): 6x6 Jacobian matrix with respect to pose j.
Note: the Ji and Jj should have shapes (6, 6) like:
| translation_variable (3-dim), rotation_variable (3-dim) |
cost_func_translation_part | * * |
cost_func_rotation_part | * * |
"""
using_optimized_compiled_one = True # recommend to use True
# fast
if using_optimized_compiled_one:
# Using the above auto-geneated functions within the copied __between_error_codegen.py file.
residual, res_D_Ti, res_D_Tj = sf_between_error_with_jacobians_func(
Ti=sym.Pose3(R=sym.rot3.Rot3(rotvec_to_quat(pose_i["r"])), t=pose_i["t"]),
Tj=sym.Pose3(R=sym.rot3.Rot3(rotvec_to_quat(pose_j["r"])), t=pose_j["t"]),
Tij=sym.Pose3(
R=sym.rot3.Rot3(rotvec_to_quat(pose_ij_meas["r"])),
t=pose_ij_meas["t"],
),
)
# ps. the reason why the index 3: mapped to :3
# is because this example uses [t, r], but symforce uses the order of [r, t]
sf_Ji = np.zeros((6, 6))
sf_Ji[:3, :3] = res_D_Ti[3:, 3:]
sf_Ji[3:, :3] = res_D_Ti[:3, 3:]
sf_Ji[:3, 3:] = res_D_Ti[3:, :3]
sf_Ji[3:, 3:] = res_D_Ti[:3, :3]
sf_Jj = np.zeros((6, 6))
sf_Jj[:3, :3] = res_D_Tj[3:, 3:]
sf_Jj[3:, :3] = res_D_Tj[:3, 3:]
sf_Jj[:3, 3:] = res_D_Tj[3:, :3]
sf_Jj[3:, 3:] = res_D_Tj[:3, :3]
residual = residual.to_tangent()
r_err, t_err = residual[:3].copy(), residual[3:].copy()
residual[:3], residual[3:] = t_err, r_err
# a verbose for debug or education,
# to compare with the hand-written, and the non-optimized Jacobians.
if False:
print("Jacobian wrt Ti:\n", sf_Jj)
print("Jacobian wrt Tj:\n", sf_Jj)
return residual, sf_Ji, sf_Jj
# slow
else:
# Create the substitutions dictionary
substitutions = {
sf_ri: sf.V3(pose_i["r"] + epsilon),
sf_ti: sf.V3(pose_i["t"] + epsilon),
sf_rj: sf.V3(pose_j["r"] + epsilon),
sf_tj: sf.V3(pose_j["t"] + epsilon),
sf_rij: sf.V3(pose_ij_meas["r"] + epsilon),
sf_tij: sf.V3(pose_ij_meas["t"] + epsilon),
}
sf_residual_val = sf_residual.subs(substitutions).to_numpy()
sf_J_ti_val = sf_J_ti.subs(substitutions).to_numpy()
sf_J_ri_val = sf_J_ri.subs(substitutions).to_numpy()
sf_J_tj_val = sf_J_tj.subs(substitutions).to_numpy()
sf_J_rj_val = sf_J_rj.subs(substitutions).to_numpy()
# ps. the reason why the index 3: mapped to :3
# is because this example uses [t, r], but symforce uses the order of [r, t]
sf_Ji = np.zeros((6, 6))
sf_Ji[:3, :3] = sf_J_ti_val[3:, :]
sf_Ji[3:, :3] = sf_J_ti_val[:3, :]
sf_Ji[:3, 3:] = sf_J_ri_val[3:, :]
sf_Ji[3:, 3:] = sf_J_ri_val[:3, :]
sf_Jj = np.zeros((6, 6))
sf_Jj[:3, :3] = sf_J_tj_val[3:, :]
sf_Jj[3:, :3] = sf_J_tj_val[:3, :]
sf_Jj[:3, 3:] = sf_J_rj_val[3:, :]
sf_Jj[3:, 3:] = sf_J_rj_val[:3, :]
residual = np.zeros(6)
residual[:3] = sf_residual_val[3:].flatten()
residual[3:] = sf_residual_val[:3].flatten()
return residual, sf_Ji, sf_Jj
@timeit
def compute_between_factor_residual_and_jacobian(
pose_i, pose_j, pose_ij_meas, use_symforce_generated_jacobian=True
):
"""
Computes the residual and Jacobians for a pair of poses given a measurement.
Parameters:
pose_i (dict): Dictionary containing rotation vector 'r' and translation 't' for pose i.
pose_j (dict): Dictionary containing rotation vector 'r' and translation 't' for pose j.
pose_ij_meas (dict): Dictionary containing rotation matrix 'R' and translation 't' from the measurement.
Returns:
residual (np.ndarray): 6-element residual vector.
Ji (np.ndarray): 6x6 (num_rows: cost-dim, by num_cols: var-dim) Jacobian matrix with respect to pose i.
Jj (np.ndarray): 6x6 (num_rows: cost-dim, by num_cols: var-dim) Jacobian matrix with respect to pose j.
"""
@timeit
def between_factor_jacobian_by_hand_approx():
# Unpack poses
ti, ri = pose_i["t"], pose_i["r"]
tj, rj = pose_j["t"], pose_j["r"]
# Convert rotation vectors to matrices
Ri = rotvec_to_rotmat(ri)
Rj = rotvec_to_rotmat(rj)
# Measurement
Rij_meas, tij_meas = pose_ij_meas["R"], pose_ij_meas["t"]
# Predicted relative transformation
Ri_inv = Ri.T
Rij_pred = Ri_inv @ Rj
tij_pred = Ri_inv @ (tj - ti)
# Error in rotation and translation
R_err = Rij_meas.T @ Rij_pred
t_err = Rij_meas.T @ (tij_pred - tij_meas)
# Map rotation error to rotation vector
r_err = rotmat_to_rotvec(R_err)
# NOTE: in this example, using [t, r] order for the tangent 6-dim vector.
residual = np.hstack((t_err, r_err))
# Jacobian w.r. to pose i
Ji = np.zeros((6, 6))
Ji[:3, :3] = -Rij_meas.T @ Ri_inv
Ji[:3, 3:] = Rij_meas.T @ Ri_inv @ skew_symmetric(tj - ti)
Ji[3:, 3:] = -np.eye(3) # approx
# Jacobian w.r. to pose j
Jj = np.zeros((6, 6))
Jj[:3, :3] = Rij_meas.T @ Ri_inv
Jj[3:, 3:] = np.eye(3) # approx
# ps. the above approximations are valid for small angle differecne
# (may differ at the early iterations wrt the symforce version)
return residual, Ji, Jj
# Compute Jacobians analytically
if use_symforce_generated_jacobian:
residual, Ji, Jj = between_factor_jacobian_by_symforce(
pose_i, pose_j, pose_ij_meas
)
else:
residual, Ji, Jj = between_factor_jacobian_by_hand_approx()
debug_compare_jacobians = False
if debug_compare_jacobians:
_, by_hand_Ji, by_hand_Jj = between_factor_jacobian_by_hand_approx()
start_time = time.perf_counter()
_, by_symb_Ji, by_symb_Jj = between_factor_jacobian_by_symforce(
pose_i, pose_j, pose_ij_meas
)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print("=" * 30, f"elapsed time: {elapsed_time:.8f} sec.")
print(f"by_hand_Ji\n {by_hand_Ji}")
print(f"by_symbolic_Ji\n {by_symb_Ji}\n")
print(f"by_hand_Jj\n {by_hand_Jj}")
print(f"by_symbolic_Jj\n {by_symb_Jj}\n\n")
return residual, Ji, Jj
class PoseGraphOptimizer:
def __init__(
self,
max_iterations=50,
initial_cauchy_c=10.0,
use_symforce_generated_jacobian=True,
num_processes=1,
use_chordal_rotation_initialization=True,
visualize3d_every_iteration=True,
loop_information_matrix=np.diag([1.0, 1.0, 1.0, 10.0, 10.0, 10.0]), # [t, r]
odom_information_matrix=np.diag([1.0, 1.0, 1.0, 10.0, 10.0, 10.0]), # [t, r]
visualize_using_open3d=True,
):
self.num_processes = num_processes
self.max_iterations = max_iterations
self.termination_threshold = 1e-1 # recommend 1e-2 to 1e-1 for the sample data
self.STATE_DIM = 6
# jacobian mode
self.use_symforce_generated_jacobian = use_symforce_generated_jacobian # if False, using Symforce-based auto-generated Symbolic Jacobian
if self.use_symforce_generated_jacobian:
print(
"\n Using symforce-based automatically derived symbolic jacobian...\n"
)
# Robust loss
self.cauchy_c = initial_cauchy_c # cauchy kernel
# LM iterative optimization
self.lambda_ = 0.001 # Initial damping factor, for LM opt
self.lambda_allowed_range = [1e-7, 1e5]
# rotation initialization
self.use_chordal_rotation_initialization = use_chordal_rotation_initialization
# weight ratio
self.loop_information_matrix = loop_information_matrix # [t, r]
self.odom_information_matrix = odom_information_matrix # [t, r]
# A single prior
self.add_prior_to_prevent_gauge_freedom = True
# misc
self.H_fig_saved = False
self.loud_verbose = True
self.visualize3d_every_iteration = visualize3d_every_iteration
self.visualize_using_open3d = visualize_using_open3d
@timeit
def read_g2o_file(self, file_path):
"""
Reads a g2o file and parses the poses and edges.
Parameters:
file_path (str): Path to the g2o file.
Returns:
poses (dict): Dictionary of poses with pose ID as keys and dictionaries containing rotation matrix 'R' and translation vector 't' as values.
edges (list): List of edges, where each edge is a dictionary containing 'from', 'to', rotation matrix 'R', translation vector 't', and 'information' matrix.
"""
self.dataset_name = file_path.split("/")[-1]
print(f"Reading (parse) {file_path} ...")
poses = {}
edges = []
def parse_information_matrix(data, size):
"""
Parses the upper triangular part of the information matrix and constructs the full symmetric matrix.
Parameters:
data (list of float): Upper triangular elements of the information matrix.
size (int): Size of the square information matrix.
Returns:
information_matrix (np.ndarray): size x size information matrix.
"""
information_upper = np.array(data)
information_matrix = np.zeros((size, size))
indices = np.triu_indices(size)
information_matrix[indices] = information_upper
information_matrix += information_matrix.T - np.diag(
information_matrix.diagonal()
)
return information_matrix
def information_matrix_wrt_edge_type(is_consecutive):
# Using a constant info matrix is more stable
if is_consecutive:
# Odometry edge
information_matrix = self.odom_information_matrix
else:
# Loop edge
information_matrix = self.loop_information_matrix
return information_matrix
def SE3_edge_dict(id_from, id_to, R, t, information_matrix):
return {
"from": id_from,
"to": id_to,
"R": R,
"t": t,
"information": information_matrix,
}
self.using_predefined_const_information_matrix_wrt_type = True
with open(file_path, "r") as f:
for line in f:
data = line.strip().split()
if not data:
continue
tag = data[0]
if tag.startswith("VERTEX"):
if tag == "VERTEX_SE3:QUAT":
node_id = int(data[1])
x, y, z = map(float, data[2:5])
qx, qy, qz, qw = map(float, data[5:9])
R = quat_to_rotmat(qx, qy, qz, qw)
t = np.array([x, y, z])
poses[node_id] = {"R": R, "t": t}
# supports both g2o and toro
elif tag == "VERTEX_SE2" or tag == "VERTEX2":
node_id = int(data[1])
x, y, theta = map(float, data[2:5])
R, t = se2_to_se3(x, y, theta)
poses[node_id] = {"R": R, "t": t}
elif tag.startswith("EDGE"):
if tag == "EDGE_SE3:QUAT":
id_from = int(data[1])
id_to = int(data[2])
x, y, z = map(float, data[3:6])
qx, qy, qz, qw = map(float, data[6:10])
R = quat_to_rotmat(qx, qy, qz, qw)
t = np.array([x, y, z])
if self.using_predefined_const_information_matrix_wrt_type:
# Using a constant info matrix seems generally more stable
information_matrix = information_matrix_wrt_edge_type(
is_consecutive=(abs(id_from - id_to) == 1)
)
else:
# The information matrix parses the original data,
information_matrix = parse_information_matrix(data[10:], 6)
edge = SE3_edge_dict(id_from, id_to, R, t, information_matrix)
edges.append(edge)
# supports both g2o and toro
elif tag == "EDGE_SE2" or tag == "EDGE2":
id_from = int(data[1])
id_to = int(data[2])
dx, dy, dtheta = map(float, data[3:6])
R, t = se2_to_se3(dx, dy, dtheta)
if self.using_predefined_const_information_matrix_wrt_type:
# Using a constant info matrix seems generally more stable
information_matrix = information_matrix_wrt_edge_type(
is_consecutive=(abs(id_from - id_to) == 1)
)
else:
# Parse the SE2 information matrix and pad it to 6x6
information_matrix_se2 = parse_information_matrix(
data[6:12], 3
)
information_matrix = np.zeros((6, 6))
information_matrix[:3, :3] = information_matrix_se2
information_matrix += np.diag(np.ones(6))
edge = SE3_edge_dict(id_from, id_to, R, t, information_matrix)
edges.append(edge)
# Convert rotations to rotation vectors
for _, pose in poses.items():
pose["r"] = rotmat_to_rotvec(pose["R"])
for edge in edges:
edge["r"] = rotmat_to_rotvec(edge["R"])
return poses, edges
def cauchy_weight(self, s):
"""
Computes the Cauchy robust kernel weight for a given residual squared norm.
The Cauchy weight reduces the influence of outliers by diminishing their contribution to the optimization.
Parameters:
s (float): The squared norm of the residual, typically computed as residual.T @ information @ residual.
Returns:
float: The computed Cauchy weight.
"""
epsilon = 1e-5
return self.cauchy_c / (np.sqrt(self.cauchy_c**2 + s) + epsilon)
def relax_rotation(self):
"""
Performs rotation initialization for the pose graph to improve the initial estimates of the rotations.
This method is called "Chordal relaxation". It minimizes the row-wise 3-dim variables L2 loss between
rotation matrices of pose i and pose j, and ensures that the updated rotation matrices remain orthogonal.
The process follows the methodology described in Section III.B of:
"Initialization Techniques for 3D SLAM: a Survey on Rotation Estimation and its Use in Pose Graph Optimization"
(2015 ICRA).
Parameters:
None
Returns:
None
Notes:
- This function modifies `self.poses_initial` in-place with the updated rotation matrices.
- It uses the Cholesky decomposition from `sksparse.cholmod` to solve the sparse linear system.
- A prior is added to fix the gauge freedom by anchoring a specific pose's rotation.
"""
num_poses = len(self.poses_initial)
variable_dim = (
3 # a single rotmat's row is a variable in the chordal relaxation
)
num_variables_per_pose = 3
num_variables = num_poses * num_variables_per_pose
num_elements_per_pose = num_variables_per_pose * variable_dim
prev_dx = None
num_epochs = 3
for epoch in range(num_epochs):
print(f" [relax_rotation] Rotation initialization epoch {epoch}")
###
### build the system
###
H_row = []
H_col = []
H_data = []
b = np.zeros(variable_dim * num_variables)
information_edge = 1.0 * np.identity(3)
#
# between factors
#
for edge in self.edges:
from_pose_id = edge["from"]
to_pose_id = edge["to"]
# note. deep copy is important here.
Ri = self.poses_initial[from_pose_id]["R"].copy()
Rj = self.poses_initial[to_pose_id]["R"].copy()
Rij_meas = edge["R"].copy()
from_pose_idx_in_matrix = self.index_map[from_pose_id]
to_pose_idx_in_matrix = self.index_map[to_pose_id]
# Iterate over each row of the rotation matrix
for row_ii in range(3):
# Compute the residual: measured rotation row - predicted rotation row (eq 21 of icra15luca)
residual = Rij_meas.T @ Ri[row_ii, :] - Rj[row_ii, :]
# Determine the weight based on whether it's a consecutive edge
if abs(from_pose_id - to_pose_id) == 1:
weight = 1.0
else:
squared_residual = residual.T @ information_edge @ residual
weight = self.cauchy_weight(squared_residual)
# Apply the weight to residual and Jacobians
weighted_residual = residual * weight
J_i = Rij_meas.T * weight # Jacobian w.r.t pose i
J_j = -np.eye(3) * weight # Jacobian w.r.t pose j
H_ii = J_i.T @ information_edge @ J_i
H_jj = J_j.T @ information_edge @ J_j
H_ij = J_i.T @ information_edge @ J_j
H_ji = J_j.T @ information_edge @ J_i
b_i = J_i.T @ information_edge @ weighted_residual
b_j = J_j.T @ information_edge @ weighted_residual
# Populate the Hessian matrix entries
from_pose_start_idx = (
num_elements_per_pose * from_pose_idx_in_matrix
)
to_pose_start_idx = num_elements_per_pose * to_pose_idx_in_matrix
variable_relative_location_within_a_pose = variable_dim * row_ii
from_variable_idx = (
from_pose_start_idx + variable_relative_location_within_a_pose
)
to_variable_idx = (
to_pose_start_idx + variable_relative_location_within_a_pose
)
for i in range(variable_dim):
for j in range(variable_dim):
H_row.append(from_variable_idx + i)
H_col.append(from_variable_idx + j)
H_data.append(H_ii[i, j])
for i in range(variable_dim):
for j in range(variable_dim):
H_row.append(to_variable_idx + i)
H_col.append(to_variable_idx + j)
H_data.append(H_jj[i, j])
for i in range(variable_dim):
for j in range(variable_dim):
H_row.append(from_variable_idx + i)
H_col.append(to_variable_idx + j)
H_data.append(H_ij[i, j])
for i in range(variable_dim):
for j in range(variable_dim):
H_row.append(to_variable_idx + i)
H_col.append(from_variable_idx + j)
H_data.append(H_ji[i, j])
# Update the gradient vector
b[from_variable_idx : from_variable_idx + variable_dim] -= b_i
b[to_variable_idx : to_variable_idx + variable_dim] -= b_j
#
# A prior factor
#
# Compute the residual (error) between current and initial estimates
pose_idx_prior = self.idx_prior
R0_meas = np.identity(3) # e.g., force to be eye
R0_est = self.poses_initial[pose_idx_prior]["R"].copy()
residual_prior = (R0_est - R0_meas).flatten()
# Jacobian of the prior (identity matrix since it's a direct difference)
J_prior = np.identity(9)
information_prior = 1e-2 * np.identity(9)
# Compute the prior's contribution to H and b
H_prior = J_prior.T @ information_prior @ J_prior
b_prior = J_prior.T @ information_prior @ residual_prior
# Append prior contributions to H_data, H_row, and H_col
for i in range(9):
for j in range(9):
H_row.append(9 * pose_idx_prior + i)
H_col.append(9 * pose_idx_prior + j)
H_data.append(H_prior[i, j])
# Update b with the prior contribution
b[(9 * pose_idx_prior) : (9 * pose_idx_prior) + 9] -= b_prior
###
### solve the system
###
H = sp.coo_matrix(
(H_data, (H_row, H_col)),
shape=(variable_dim * num_variables, variable_dim * num_variables),
)
H = H.tocsc()
factor = cholmod.cholesky(H)
delta_x = factor.solve_A(b)
delta_x_norm = np.linalg.norm(delta_x)
if prev_dx is None:
dx_gain = delta_x_norm
else:
dx_gain = np.linalg.norm(prev_dx - delta_x)
prev_dx = delta_x
print(
f" - Epoch {epoch}, rot rows vec dx shape: {delta_x.shape}",
f"dx={delta_x}, norm(dx): {np.linalg.norm(delta_x):.5f}, dx gain: {dx_gain:.5f}",
)
###
### update the rotmats
###
def eq23icra15luca(M):
U, D, Vt = np.linalg.svd(M)
det_sign = np.sign(np.linalg.det(U @ Vt))
S = np.diag([1, 1, det_sign])
R_star = U @ S @ Vt
return R_star
for pose_id, pose in self.poses_initial.items():
R_orig = pose["R"].copy()
M = R_orig.copy() # eq 22, icra15, Luca Carlone, et al.
for row_ii in range(3):
pose_idx_in_matrix = self.index_map[pose_id]
delta_x_block = delta_x[
(num_elements_per_pose * pose_idx_in_matrix)
+ (variable_dim * row_ii) : (
num_elements_per_pose * pose_idx_in_matrix
)
+ (variable_dim * row_ii)
+ variable_dim
]
M[row_ii, :] += delta_x_block
R_star = eq23icra15luca(M)
self.poses_initial[pose_id]["R"] = R_star
self.poses_initial[pose_id]["r"] = rotmat_to_rotvec(R_star)
print(f"\nChordal relaxation for the rotation initialization is completed.\n")
def initialize_variables_container(self, index_map):
"""
Initializes the state vector containing all pose variables.
The state vector `x` is initialized to zeros and populated with the initial translations and rotation vectors
for each pose based on the provided `poses_initial` data.
Parameters:
index_map (dict): A mapping from pose IDs to their corresponding indices in the state vector.
Returns:
np.ndarray: The initialized state vector with shape (6 * number_of_poses,).
"""
if self.use_chordal_rotation_initialization:
self.relax_rotation()
x = np.zeros(6 * self.num_poses)
for pose_id, pose in self.poses_initial.items():
idx = index_map[pose_id]
t = pose["t"]
r = pose["r"]