Debian Codegraph @

src/thirdparty/Symforce-Caspar/caspar_generate.py

raw
1 # Usage:
2 # python generate_caspar.py <out_dir> [f32|f64]
3
4 import inspect
5 import sys
6 from itertools import combinations
7 from pathlib import Path
8 from typing import Annotated, get_type_hints
9
10 # Must be set before importing symforce.symbolic
11 precision = sys.argv[2] if len(sys.argv) > 2 else "f32"
12
13 if precision not in ("f32", "f64"):
14 print(f"ERROR: Unknown precision '{precision}'. Expected f32 or f64.")
15 sys.exit(1)
16
17 import symforce # noqa: E402
18
19 symforce.set_epsilon_to_number(1e-15 if precision == "f64" else 1e-6)
20
21 import symforce.symbolic as sf # noqa: E402
22 from symforce import typing as T # noqa: E402
23 from symforce.caspar import CasparLibrary # noqa: E402
24 from symforce.caspar import memory as mem # noqa: E402
25
26
27 # Point and ConstPoint are shared across camera models so that different
28 # camera types can observe the same 3D points in the same node pool.
29 class Point(sf.V3):
30 pass
31
32
33 class ConstPoint(sf.V3):
34 pass
35
36
37 class ConstPixel(sf.V2):
38 pass
39
40
41 # Calibration node layout:
42 #
43 # When both focal_and_extra/focal and principal_point are tunable, they
44 # are merged into a single V4 Calib node to save one shared-memory slot per
45 # block.
46 # This covers 4 variants: BASE, FIXED_POSE, FIXED_POINT, FIXED_POSE_FIXED_POINT.
47 #
48 # When at least one group is fixed, split V2 nodes are used (11 variants).
49 # Total: 4 merged + 11 split = 15 variants per camera model.
50 #
51 # Pose and Calib nodes are camera-model-specific to prevent cross-model
52 # batching.
53 # Check that generated kernels stay within the 48 KB shared memory limit if
54 # adding new parameter groups.
55
56
57 # SimpleRadial: params = [f, cx, cy, k]
58 class SimpleRadialPose(sf.Pose3):
59 pass
60
61
62 class ConstSimpleRadialPose(sf.Pose3):
63 pass
64
65
66 class SimpleRadialCalib(sf.V4):
67 pass # [f, k, cx, cy] (merged)
68
69
70 class ConstSimpleRadialCalib(sf.V4):
71 pass
72
73
74 class SimpleRadialPrincipalPoint(sf.V2):
75 pass # [cx, cy] (split: pp tunable)
76
77
78 class ConstSimpleRadialPrincipalPoint(sf.V2):
79 pass
80
81
82 class SimpleRadialFocalAndExtra(sf.V2):
83 pass # [f, k] (split: focal tunable)
84
85
86 class ConstSimpleRadialFocalAndExtra(sf.V2):
87 pass
88
89
90 # Pinhole: params = [fx, fy, cx, cy]
91 class PinholePose(sf.Pose3):
92 pass
93
94
95 class ConstPinholePose(sf.Pose3):
96 pass
97
98
99 class PinholeCalib(sf.V4):
100 pass # [fx, fy, cx, cy] (merged)
101
102
103 class ConstPinholeCalib(sf.V4):
104 pass
105
106
107 class PinholePrincipalPoint(sf.V2):
108 pass # [cx, cy] (split: pp tunable)
109
110
111 class ConstPinholePrincipalPoint(sf.V2):
112 pass
113
114
115 class PinholeFocal(sf.V2):
116 pass # [fx, fy] (split: focal tunable)
117
118
119 class ConstPinholeFocal(sf.V2):
120 pass
121
122
123 # Constant sensor-from-rig calibration, stored as ConstantSequential
124 # (7 floats = 28 B f32 / 56 B f64 loaded from global memory per factor).
125 # ConstantShared would deduplicate to one slot per unique sensor per block,
126 # eliminating the per-factor global loads, but Caspar incorrectly counts
127 # ConstantShared nodes against the 48 KB shared-memory budget even though they
128 # are never loaded into shared memory. Switch to ConstantShared once fixed.
129 # This choice does not affect Jacobian correctness: rig linkage is encoded
130 # through the shared rig_from_world pose node (same pose index for all sensors
131 # in a frame), not through sensor_from_rig.
132 class ConstSimpleRadialSensorFromRig(sf.Pose3):
133 pass
134
135
136 class ConstPinholeSensorFromRig(sf.Pose3):
137 pass
138
139
140 def _make_variant(
141 core_fn, name: str, base_params: list, hints: dict, fixed: dict
142 ):
143 new_hints = {}
144 for p in base_params:
145 if p in fixed:
146 new_hints[p] = Annotated[fixed[p], mem.ConstantSequential]
147 else:
148 new_hints[p] = hints[p]
149
150 tunable_params = [p for p in base_params if p not in fixed]
151 const_params = [p for p in base_params if p in fixed]
152 ordered = tunable_params + const_params
153
154 # Caspar calls factors as fn(**symbolic_args), so the wrapper accepts both
155 # positional and keyword arguments.
156 def wrapper(*args, **kwargs):
157 merged = {**dict(zip(ordered, args, strict=False)), **kwargs}
158 return core_fn(*[merged[p] for p in base_params])
159
160 wrapper.__name__ = name
161 wrapper.__annotations__ = {p: new_hints[p] for p in ordered}
162 wrapper.__annotations__["return"] = hints.get("return")
163 wrapper.__signature__ = inspect.Signature(
164 [
165 inspect.Parameter(p, inspect.Parameter.POSITIONAL_OR_KEYWORD)
166 for p in ordered
167 ]
168 )
169 return wrapper
170
171
172 def register_camera_model(
173 caslib,
174 model_name: str,
175 core_fn,
176 fixable_params: dict,
177 must_fix_one_of: T.Optional[set] = None,
178 include_all_fixed: bool = False,
179 ):
180 hints = get_type_hints(core_fn, include_extras=True)
181 base_params = list(inspect.signature(core_fn).parameters.keys())
182 fixable_items = list(fixable_params.items())
183
184 # include_all_fixed extends the range to N for merged-calib models, where
185 # the "all-fixed" subset still has a tunable Calib node.
186 max_r = len(fixable_items) + (1 if include_all_fixed else 0)
187 for r in range(max_r):
188 for combo in combinations(fixable_items, r):
189 fixed = dict(combo)
190
191 # Skip split variants where both calib groups are tunable, as those
192 # are handled by the merged-calib registration.
193 if must_fix_one_of and not any(p in fixed for p in must_fix_one_of):
194 continue
195
196 if fixed:
197 # Suffix order follows fixable_params definition order to
198 # match the C++ dispatch naming.
199 suffix = "_".join(
200 f"fixed_{p}" for p, _ in fixable_items if p in fixed
201 )
202 name = f"{model_name}_{suffix}"
203 else:
204 name = model_name
205
206 caslib.add_factor(
207 _make_variant(core_fn, name, base_params, hints, fixed)
208 )
209
210
211 # --- Camera models ---
212
213 # Merged cores define the canonical projection math reused by split variants.
214
215
216 def simple_radial_core(
217 pose: T.Annotated[SimpleRadialPose, mem.TunableShared],
218 sensor_from_rig: T.Annotated[
219 ConstSimpleRadialSensorFromRig, mem.ConstantSequential
220 ],
221 calib: T.Annotated[SimpleRadialCalib, mem.TunableShared], # [f, k, cx, cy]
222 point: T.Annotated[Point, mem.TunableShared],
223 pixel: T.Annotated[ConstPixel, mem.ConstantSequential],
224 ) -> sf.V2:
225 """Reprojection residual for COLMAP's SIMPLE_RADIAL model (sensor/models.h).
226
227 calib = [f, k, cx, cy]: single focal length, one radial distortion
228 coefficient, and principal point.
229 pose holds rig_from_world; sensor_from_rig is identity for single-camera
230 rigs (cam_from_world == rig_from_world in that case).
231 """
232 cam_T_world = sensor_from_rig * pose
233 f, k, cx, cy = calib
234 point_cam = cam_T_world * point
235 depth = point_cam[2]
236 p = sf.V2(point_cam[:2]) / (depth + sf.epsilon() * sf.sign_no_zero(depth))
237 r = 1 + k * p.squared_norm()
238 return f * r * p + sf.V2([cx, cy]) - pixel
239
240
241 def pinhole_core(
242 pose: T.Annotated[PinholePose, mem.TunableShared],
243 sensor_from_rig: T.Annotated[
244 ConstPinholeSensorFromRig, mem.ConstantSequential
245 ],
246 calib: T.Annotated[PinholeCalib, mem.TunableShared], # [fx, fy, cx, cy]
247 point: T.Annotated[Point, mem.TunableShared],
248 pixel: T.Annotated[ConstPixel, mem.ConstantSequential],
249 ) -> sf.V2:
250 """Reprojection residual for COLMAP's PINHOLE model (sensor/models.h).
251
252 calib = [fx, fy, cx, cy]: two independent focal lengths and principal point,
253 no distortion.
254 pose holds rig_from_world; sensor_from_rig is identity for single-camera
255 rigs (cam_from_world == rig_from_world in that case).
256 """
257 cam_T_world = sensor_from_rig * pose
258 fx, fy, cx, cy = calib
259 point_cam = cam_T_world * point
260 depth = point_cam[2]
261 p = sf.V2(point_cam[:2]) / (depth + sf.epsilon() * sf.sign_no_zero(depth))
262 return sf.V2([fx * p[0] + cx, fy * p[1] + cy]) - pixel
263
264
265 # Split cores delegate to merged cores to avoid duplicating projection math.
266
267
268 def simple_radial_split_core(
269 pose: T.Annotated[SimpleRadialPose, mem.TunableShared],
270 sensor_from_rig: T.Annotated[
271 ConstSimpleRadialSensorFromRig, mem.ConstantSequential
272 ],
273 focal_and_extra: T.Annotated[SimpleRadialFocalAndExtra, mem.TunableShared],
274 principal_point: T.Annotated[SimpleRadialPrincipalPoint, mem.TunableShared],
275 point: T.Annotated[Point, mem.TunableShared],
276 pixel: T.Annotated[ConstPixel, mem.ConstantSequential],
277 ) -> sf.V2:
278 """Split-calib variant of simple_radial_core.
279
280 For COLMAP's SIMPLE_RADIAL model. Used when focal/extra and principal
281 point are tuned independently.
282 focal_and_extra = [f, k], principal_point = [cx, cy].
283 """
284 calib = sf.V4(
285 [
286 focal_and_extra[0],
287 focal_and_extra[1],
288 principal_point[0],
289 principal_point[1],
290 ]
291 )
292 return simple_radial_core(pose, sensor_from_rig, calib, point, pixel)
293
294
295 def pinhole_split_core(
296 pose: T.Annotated[PinholePose, mem.TunableShared],
297 sensor_from_rig: T.Annotated[
298 ConstPinholeSensorFromRig, mem.ConstantSequential
299 ],
300 focal: T.Annotated[PinholeFocal, mem.TunableShared],
301 principal_point: T.Annotated[PinholePrincipalPoint, mem.TunableShared],
302 point: T.Annotated[Point, mem.TunableShared],
303 pixel: T.Annotated[ConstPixel, mem.ConstantSequential],
304 ) -> sf.V2:
305 """Split-calib variant of pinhole_core for COLMAP's PINHOLE model.
306
307 Used when focal lengths and principal point are tuned independently.
308 focal = [fx, fy], principal_point = [cx, cy].
309 """
310 calib = sf.V4([focal[0], focal[1], principal_point[0], principal_point[1]])
311 return pinhole_core(pose, sensor_from_rig, calib, point, pixel)
312
313
314 dtype = mem.DType.DOUBLE if precision == "f64" else mem.DType.FLOAT
315 caslib = CasparLibrary(name="caspar_lib", dtype=dtype)
316
317
318 # Suffix order defines generated variant names and must match the C++ dispatch
319 # logic that builds names from BundleAdjustmentOptions.
320 #
321 # COLMAP flag mapping:
322 # refine_rig_from_world -> pose
323 # refine_focal_length && refine_extra_params -> focal_and_extra / focal
324 # refine_principal_point -> principal_point
325 # refine_points3D -> point
326 #
327 # Limitations:
328 # - constant_rig_from_world_rotation not supported (needs separate pose
329 # rotation/translation sub-nodes)
330 # - refine_sensor_from_rig=true not supported (tunable sensor_from_rig would
331 # need a second Pose3 node, likely overflowing the 48 KB limit without
332 # splitting Pose3 into rotation/translation sub-nodes)
333 # - refine_focal_length != refine_extra_params not supported (observations
334 # skipped with a warning because the merged focal_and_extra node
335 # cannot be split)
336 #
337 # sensor_from_rig is always present as a ConstantShared parameter. For single-
338 # camera datasets the host passes identity, making it a no-op. For multi-camera
339 # rigs it carries the per-sensor extrinsic calibration.
340
341 FIXABLE_SIMPLE_RADIAL = {
342 "pose": ConstSimpleRadialPose,
343 "point": ConstPoint,
344 }
345
346 FIXABLE_PINHOLE = {
347 "pose": ConstPinholePose,
348 "point": ConstPoint,
349 }
350
351 FIXABLE_SIMPLE_RADIAL_SPLIT = {
352 "pose": ConstSimpleRadialPose,
353 "focal_and_extra": ConstSimpleRadialFocalAndExtra,
354 "principal_point": ConstSimpleRadialPrincipalPoint,
355 "point": ConstPoint,
356 }
357
358 FIXABLE_PINHOLE_SPLIT = {
359 "pose": ConstPinholePose,
360 "focal": ConstPinholeFocal,
361 "principal_point": ConstPinholePrincipalPoint,
362 "point": ConstPoint,
363 }
364
365 # Merged: BASE, FIXED_POSE, FIXED_POINT, FIXED_POSE_FIXED_POINT (4 variants).
366 register_camera_model(
367 caslib,
368 "simple_radial",
369 simple_radial_core,
370 FIXABLE_SIMPLE_RADIAL,
371 include_all_fixed=True,
372 )
373 register_camera_model(
374 caslib, "pinhole", pinhole_core, FIXABLE_PINHOLE, include_all_fixed=True
375 )
376
377 # Split: all variants where at least one of
378 # {focal_and_extra, principal_point} is fixed (11 variants per model).
379 register_camera_model(
380 caslib,
381 "simple_radial_split",
382 simple_radial_split_core,
383 FIXABLE_SIMPLE_RADIAL_SPLIT,
384 must_fix_one_of={"focal_and_extra", "principal_point"},
385 )
386 register_camera_model(
387 caslib,
388 "pinhole_split",
389 pinhole_split_core,
390 FIXABLE_PINHOLE_SPLIT,
391 must_fix_one_of={"focal", "principal_point"},
392 )
393
394 out_dir = Path(f"{sys.argv[1]}")
395 print(f"Generating Caspar kernels with precision {precision}: {out_dir}")
396 caslib.generate(out_dir, use_symlinks=False, python_bindings=False)