Debian Codegraph @

benchmark/reconstruction/evaluation/utils.py

raw
1 # Copyright (c), ETH Zurich and UNC Chapel Hill.
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6 #
7 # * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #
10 # * Redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution.
13 #
14 # * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
15 # its contributors may be used to endorse or promote products derived
16 # from this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29
30 import argparse
31 import collections
32 import copy
33 import ctypes
34 import dataclasses
35 import datetime
36 import functools
37 import itertools
38 import multiprocessing
39 import pickle
40 import platform
41 import shutil
42 import signal
43 import subprocess
44 import sys
45 import threading
46 from abc import ABC, abstractmethod
47 from collections.abc import Iterable, Sequence
48 from pathlib import Path
49
50 import numpy as np
51 import numpy.typing as npt
52
53 import pycolmap
54 from pycolmap import panorama
55
56 from .covisibility import filter_covisibility # noqa: F401
57 from .geometry import normalize_vec, vec_angular_dist_deg # noqa: F401
58
59 # Sentinel GT component id in image_name_to_component marking an outlier image
60 # that does not belong to any GT reconstruction. Outliers are never part of a
61 # GT edge (relative metric) or a GT component (absolute metric).
62 OUTLIER_COMPONENT_ID = -1
63
64 _PR_SET_PDEATHSIG = 1
65 _LIBC = (
66 ctypes.CDLL("libc.so.6", use_errno=True)
67 if platform.system() == "Linux"
68 else None
69 )
70
71
72 def _set_pdeathsig() -> None:
73 """preexec_fn: ensure child process is killed if parent dies."""
74 if _LIBC is not None:
75 _LIBC.prctl(_PR_SET_PDEATHSIG, signal.SIGTERM)
76
77
78 def _init_pool_worker() -> None:
79 """Pool initializer: ignore SIGINT in workers so the main process
80 handles KeyboardInterrupt and terminates the pool cleanly."""
81 signal.signal(signal.SIGINT, signal.SIG_IGN)
82
83
84 def _run_with_log(
85 cmd: list, log_path: Path, check: bool = True, **kwargs
86 ) -> int:
87 """Run a subprocess, redirecting stdout+stderr to log_path (overwrite).
88
89 Uses preexec_fn=_set_pdeathsig on Linux so children die with their parent.
90 preexec_fn is unavailable on Windows, and PR_SET_PDEATHSIG is
91 Linux-specific. Raises CalledProcessError on non-zero exit when check=True.
92 """
93 log_path.parent.mkdir(parents=True, exist_ok=True)
94 with open(log_path, "wb") as fh:
95 runner = subprocess.check_call if check else subprocess.call
96 popen_kwargs = dict(stdout=fh, stderr=subprocess.STDOUT, **kwargs)
97 if platform.system() != "Windows":
98 popen_kwargs["preexec_fn"] = _set_pdeathsig
99 return runner(cmd, **popen_kwargs)
100
101
102 @dataclasses.dataclass(kw_only=True)
103 class SceneInfo:
104 # Dataset name.
105 dataset: str
106 # Category name.
107 category: str
108 # Scene name.
109 scene: str
110 # Number of input images in the scene.
111 num_images: int
112 # Path to the workspace directory in the run directory.
113 workspace_path: Path
114 # Path to the input images.
115 image_path: Path
116 # Path to the ground-truth sparse reconstruction.
117 sparse_gt_path: Path
118 # Whether the dataset has camera priors.
119 has_camera_priors: bool
120 # Additional arguments for the COLMAP reconstruction command.
121 colmap_extra_args: list[str]
122 # Reconstruction backend. The default uses automatic_reconstructor.
123 reconstruction_backend: str = "automatic"
124 # Subdirectory below workspace_path containing models to evaluate.
125 reconstruction_subdir: str = "sparse"
126 covisibility_path: Path | None = None
127 covisibility_min_shared_points: int | None = None
128 # Maps image name -> ground-truth component id. Images sharing an id
129 # belong to the same GT reconstruction (this defines the GT edge set for
130 # the relative metric and the component for the absolute metric). Empty
131 # means the scene ships a single GT reconstruction; process_scene then
132 # materializes a default {name: 0 for every sparse_gt image}. This is the
133 # case for all current datasets that ship one GT model per scene.
134 image_name_to_component: dict[str, int] = dataclasses.field(
135 default_factory=dict
136 )
137
138
139 @dataclasses.dataclass(kw_only=True)
140 class SceneResult:
141 # Scene information for which the result was computed.
142 scene_info: SceneInfo
143 # Flat list of errors.
144 errors: npt.NDArray[np.floating]
145 # Number of images in the scene.
146 num_images: int
147 # Number of registered images in the scene (over all components).
148 num_reg_images: int
149 # Number of components in the scene.
150 num_components: int
151 # Number of images in the largest component.
152 largest_component: int
153
154
155 @dataclasses.dataclass(kw_only=True)
156 class Metrics:
157 # Recall at specified error thresholds.
158 recalls: npt.NDArray[np.floating]
159 # Area under the curve (AUC) scores at specified error thresholds.
160 aucs: npt.NDArray[np.floating]
161 error_thresholds: npt.NDArray[np.floating]
162 error_type: str
163 # Number of images in the scene.
164 num_images: int
165 # Number of registered images in the scene (over all components).
166 num_reg_images: int
167 # Number of components in the scene.
168 num_components: int
169 # Number of images in the largest component.
170 largest_component: int
171 # Raw errors that produced aucs/recalls. Empty for entries (like __avg__)
172 # where no underlying error pool exists. Retained so higher-level summaries
173 # (per-dataset, overall) can recompute pooled __all__ statistics.
174 errors: npt.NDArray[np.floating] = dataclasses.field(
175 default_factory=lambda: np.array([])
176 )
177 # Ground-truth position accuracy (used as min_error when computing AUC).
178 # Carried so cross-dataset aggregations can pick a sensible value.
179 position_accuracy_gt: float = 0.0
180
181
182 MetricsByScene = dict[str, Metrics]
183 MetricsByCatByScene = dict[str, MetricsByScene]
184 MetricsByDatasetByCatByScene = dict[str, MetricsByCatByScene]
185
186 # Identifies one scene across reports: (dataset, category, scene).
187 SceneKey = tuple[str, str, str]
188
189
190 class Dataset(ABC):
191 def __init__(
192 self,
193 data_path: Path,
194 categories: list[str],
195 scenes: list[Path],
196 run_path: Path,
197 run_name: str,
198 ):
199 self.data_path = data_path
200 self.categories = categories
201 self.scenes = scenes
202 self.run_path = run_path
203 self.run_name = run_name
204
205 @property
206 @abstractmethod
207 def position_accuracy_gt(self) -> float:
208 """Ground-truth position accuracy in meters."""
209 pass
210
211 @property
212 @abstractmethod
213 def supports_covisibility_filtering(self) -> bool:
214 """Whether the GT reconstruction can drive covisibility filtering.
215
216 The frustum/track-based filter needs a GT reconstruction with real
217 intrinsics (and ideally 3D points) in a shared gauge. Datasets whose GT
218 lacks these (e.g. IMC2025 with placeholder cameras) must return False
219 so process_scene does not pass their GT to the filter.
220 """
221 pass
222
223 @abstractmethod
224 def list_scenes(self) -> list[SceneInfo]:
225 """List all scenes to evaluate."""
226 pass
227
228 @abstractmethod
229 def prepare_scene(self, scene_info: SceneInfo) -> None:
230 """Prepare the scene for reconstruction."""
231 pass
232
233
234 class _PhaseTracker:
235 """Worker-side helper that publishes the current phase for a scene to a
236 shared dict. No-op when status_dict is None."""
237
238 def __init__(self, status_dict=None, scene_key: str = "") -> None:
239 self._dict = status_dict
240 self._key = scene_key
241
242 def set(self, phase: str) -> None:
243 if self._dict is not None:
244 self._dict[self._key] = phase
245
246
247 def _scene_key(scene_info: SceneInfo) -> str:
248 return f"{scene_info.dataset}/{scene_info.category}/{scene_info.scene}"
249
250
251 def _run_progress_monitor(
252 status_dict, total: int, stop_event: threading.Event
253 ) -> None:
254 """Render a live progress display of in-flight scenes until stop_event is
255 set. Counts entries marked "done" toward overall completion; everything
256 else is shown as an in-progress task with a spinner and elapsed time."""
257 from rich.console import Group
258 from rich.live import Live
259 from rich.progress import (
260 BarColumn,
261 MofNCompleteColumn,
262 Progress,
263 SpinnerColumn,
264 TextColumn,
265 TimeElapsedColumn,
266 )
267
268 overall = Progress(
269 TextColumn("[bold]Scenes[/bold]"),
270 BarColumn(),
271 MofNCompleteColumn(),
272 TimeElapsedColumn(),
273 )
274 scenes = Progress(
275 SpinnerColumn(),
276 TextColumn("{task.description}"),
277 TextColumn("[cyan]{task.fields[phase]:>14}[/cyan]"),
278 TimeElapsedColumn(),
279 )
280 overall_task = overall.add_task("scenes", total=total)
281 scene_tasks: dict[str, int] = {}
282
283 def refresh() -> None:
284 snapshot = dict(status_dict)
285 done = sum(1 for v in snapshot.values() if v == "finished")
286 overall.update(overall_task, completed=done)
287 in_progress = {k: v for k, v in snapshot.items() if v != "finished"}
288 for key in list(scene_tasks):
289 if key not in in_progress:
290 scenes.remove_task(scene_tasks.pop(key))
291 for key, phase in in_progress.items():
292 if key in scene_tasks:
293 scenes.update(scene_tasks[key], phase=phase)
294 else:
295 scene_tasks[key] = scenes.add_task(key, total=None, phase=phase)
296
297 with Live(Group(overall, scenes), refresh_per_second=4):
298 while not stop_event.is_set():
299 refresh()
300 stop_event.wait(0.5)
301 refresh()
302
303
304 def filter_smallest_scenes_per_category(
305 scene_infos: list[SceneInfo], num_scenes: int
306 ) -> list[SceneInfo]:
307 """Keep only the `num_scenes` smallest scenes (by num_images) per category,
308 preserving the original order."""
309 indices_by_category: dict[str, list[int]] = collections.defaultdict(list)
310 for i, scene_info in enumerate(scene_infos):
311 indices_by_category[scene_info.category].append(i)
312
313 keep: set[int] = set()
314 for indices in indices_by_category.values():
315 smallest = sorted(indices, key=lambda i: scene_infos[i].num_images)[
316 :num_scenes
317 ]
318 keep.update(smallest)
319
320 return [scene_infos[i] for i in sorted(keep)]
321
322
323 def parse_args(description: str | None = None) -> argparse.Namespace:
324 datetime_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
325
326 parser = argparse.ArgumentParser(
327 description=description,
328 formatter_class=argparse.RawDescriptionHelpFormatter,
329 )
330 parser.add_argument(
331 "--data_path", default=Path(__file__).parent.parent / "data", type=Path
332 )
333 parser.add_argument(
334 "--datasets",
335 nargs="+",
336 default=["eth3d", "blended-mvs", "imc2023", "imc2024"],
337 )
338 parser.add_argument(
339 "--categories",
340 nargs="+",
341 default=[],
342 help="Categories to evaluate, if empty all categories are evaluated.",
343 )
344 parser.add_argument(
345 "--scenes",
346 nargs="+",
347 default=[],
348 help="Scenes to evaluate, if empty all scenes are evaluated.",
349 )
350 parser.add_argument(
351 "--progress",
352 default=None,
353 action=argparse.BooleanOptionalAction,
354 help="Show a live progress display of in-flight scenes "
355 "(default: enabled when stdout is a TTY).",
356 )
357 parser.add_argument(
358 "--fast",
359 default=False,
360 action="store_true",
361 help="Fast mode: only evaluate the N smallest scenes per category, "
362 "where N is set by --fast_num_scenes.",
363 )
364 parser.add_argument(
365 "--fast_num_scenes",
366 type=int,
367 default=1,
368 help="Number of smallest scenes per category to evaluate in --fast "
369 "mode.",
370 )
371 parser.add_argument(
372 "--run_path", default=Path(__file__).parent.parent / "runs", type=Path
373 )
374 parser.add_argument("--run_name", default=datetime_str)
375 parser.add_argument(
376 "--report_name",
377 default=f"report-{datetime_str}",
378 help="Report file stem, without the .pkl suffix. With "
379 "--seeds/--num_seeds it is the stem of every run, which are written "
380 "as <report_name>_s<seed>.pkl; compare.py reads that naming back via "
381 "--report_a_path_prefix/--report_b_path_prefix.",
382 )
383 parser.add_argument(
384 "--overwrite_database", default=False, action="store_true"
385 )
386 parser.add_argument(
387 "--overwrite_matches", default=False, action="store_true"
388 )
389 parser.add_argument(
390 "--overwrite_two_view_geometries",
391 default=False,
392 action="store_true",
393 help="Clear two-view geometries (inlier matches) but keep raw matches, "
394 "so geometric verification is recomputed from the cached matches. "
395 "Useful for re-tuning geometric verification without re-matching.",
396 )
397 parser.add_argument(
398 "--overwrite_reconstruction", default=False, action="store_true"
399 )
400 parser.add_argument(
401 "--overwrite_alignment", default=False, action="store_true"
402 )
403 parser.add_argument("--colmap_path", required=True)
404 parser.add_argument("--use_gpu", default=True, action="store_true")
405 parser.add_argument("--use_cpu", dest="use_gpu", action="store_false")
406 parser.add_argument(
407 "--num_threads",
408 type=int,
409 default=-1,
410 help=(
411 "Total number of threads to use across all parallel scenes. "
412 "Defaults to 2x the number of logical CPU cores (-1)."
413 ),
414 )
415 parser.add_argument(
416 "--num_parallel_scenes",
417 type=int,
418 default=-1,
419 help=(
420 "Number of scenes to reconstruct in parallel. "
421 "Defaults to max(1, num_threads // 4) (-1)."
422 ),
423 )
424 parser.add_argument(
425 "--threads_per_scene",
426 type=int,
427 default=-1,
428 help=(
429 "Override the number of threads used within each scene. "
430 "Defaults to num_threads // num_parallel_scenes (-1). Set to 1 "
431 "for reproducible runs: RANSAC seeds per thread as "
432 "random_seed + omp_get_thread_num(), so with a fixed --random_seed "
433 "only single-threaded scenes are deterministic (required for "
434 "paired common-random-number A/B comparison)."
435 ),
436 )
437 parser.add_argument(
438 "--gpu_index",
439 type=str,
440 default="-1",
441 help="GPU indices to use for reconstruction. "
442 "Use '-1' to auto-detect and use all available GPUs. "
443 "Use comma-separated indices like '0,1,2' to specify exact GPUs.",
444 )
445 parser.add_argument(
446 "--random_seed",
447 type=int,
448 default=-1,
449 help="Random seed forwarded to colmap's automatic_reconstructor "
450 "(two-view RANSAC + mapper). -1 (default) uses a nondeterministic "
451 "random device, matching prior harness behavior. Fix it to a "
452 "non-negative value for reproducible / paired A-B runs.",
453 )
454 seed_group = parser.add_mutually_exclusive_group()
455 seed_group.add_argument(
456 "--seeds",
457 type=int,
458 nargs="+",
459 default=None,
460 help="Run the evaluation once per seed, writing "
461 "<report_name>_s<seed>.pkl each time, to measure run-to-run spread. "
462 "Mutually exclusive with --random_seed.",
463 )
464 seed_group.add_argument(
465 "--num_seeds",
466 type=int,
467 default=None,
468 help="Shorthand for --seeds 0 1 ... N-1.",
469 )
470 parser.add_argument(
471 "--feature",
472 default="sift",
473 choices=["sift", "aliked", "loma", "loma128"],
474 )
475 parser.add_argument(
476 "--mapper",
477 default="incremental",
478 choices=["incremental", "hierarchical", "global"],
479 )
480 parser.add_argument(
481 "--quality", default="high", choices=["low", "medium", "high"]
482 )
483 parser.add_argument(
484 "--uncalibrated",
485 default=False,
486 action="store_true",
487 help="Whether to evaluate the setting of uncalibrated input cameras, "
488 "even if normal setting for the dataset contains calibrated inputs. "
489 "This is useful for evaluating the performance of self-calibration.",
490 )
491 parser.add_argument(
492 "--filter_covisibility",
493 default=True,
494 action=argparse.BooleanOptionalAction,
495 help="Filter out non-covisible image pairs based on GT camera poses. "
496 "Use --no-filter_covisibility to disable.",
497 )
498 parser.add_argument(
499 "--covisibility_frustum_near",
500 type=float,
501 default=None,
502 help="Near plane for frustum co-visibility check. "
503 "Auto-detected from GT points if not specified.",
504 )
505 parser.add_argument(
506 "--covisibility_frustum_far",
507 type=float,
508 default=None,
509 help="Far plane for frustum co-visibility check. "
510 "Auto-detected from GT points if not specified.",
511 )
512 parser.add_argument(
513 "--covisibility_max_viewing_angle",
514 type=float,
515 default=120.0,
516 help="Maximum viewing angle in degrees for co-visibility check.",
517 )
518 parser.add_argument(
519 "--covisibility_min_shared_points",
520 type=int,
521 default=5,
522 help="Minimum number of shared GT 3D points for two images to be "
523 "considered covisible. If GT tracks are available and this is > 0, "
524 "track-based covisibility is preferred over frustum-based checking.",
525 )
526 parser.add_argument(
527 "--error_type",
528 default="relative_auc",
529 choices=[
530 "relative_auc",
531 "absolute_auc",
532 "relative_recall",
533 "absolute_recall",
534 ],
535 help="Whether to evaluate relative pairwise pose errors in angular "
536 "distance or absolute pose errors through GT alignment.",
537 )
538 parser.add_argument(
539 "--rel_error_thresholds",
540 type=float,
541 nargs="+",
542 default=[0.5, 1, 5, 10],
543 help="Evaluation thresholds in degrees.",
544 )
545 parser.add_argument(
546 "--abs_error_thresholds",
547 type=float,
548 nargs="+",
549 default=[0.02, 0.05, 0.2, 0.5],
550 help="Evaluation thresholds in meters.",
551 )
552 args = parser.parse_args()
553 args.colmap_path = Path(args.colmap_path).resolve()
554 if args.num_seeds is not None:
555 if args.num_seeds <= 0:
556 parser.error("--num_seeds must be > 0")
557 args.seeds = list(range(args.num_seeds))
558 if args.seeds is not None:
559 if args.random_seed >= 0:
560 parser.error(
561 "--random_seed sets the seed of a single run; use "
562 "--seeds/--num_seeds to run once per seed"
563 )
564 if any(seed < 0 for seed in args.seeds):
565 parser.error("--seeds must be non-negative")
566 # Names the flag the user actually passed, so the non-determinism warning
567 # does not point at --random_seed during a --seeds/--num_seeds run.
568 args.seed_flag = "--seeds" if args.seeds is not None else "--random_seed"
569 if args.fast and args.fast_num_scenes <= 0:
570 parser.error("--fast_num_scenes must be > 0 when --fast is set")
571 if args.progress is None:
572 args.progress = sys.stdout.isatty()
573 if args.num_threads <= 0:
574 args.num_threads = 2 * multiprocessing.cpu_count()
575 if args.num_parallel_scenes <= 0:
576 args.num_parallel_scenes = max(1, args.num_threads // 4)
577 if args.overwrite_database:
578 pycolmap.logging.info(
579 "Overwriting database also overwrites reconstruction"
580 )
581 args.overwrite_reconstruction = True
582 if args.overwrite_matches:
583 pycolmap.logging.info(
584 "Overwriting matches also overwrites reconstruction"
585 )
586 args.overwrite_reconstruction = True
587 if args.overwrite_two_view_geometries:
588 pycolmap.logging.info(
589 "Overwriting two-view geometries also overwrites reconstruction"
590 )
591 args.overwrite_reconstruction = True
592 if args.overwrite_reconstruction:
593 pycolmap.logging.info(
594 "Overwriting reconstruction also overwrites alignment"
595 )
596 args.overwrite_alignment = True
597 return args
598
599
600 def set_camera_priors(
601 database_path: Path, camera_priors_sparse_gt: pycolmap.Reconstruction
602 ) -> None:
603 pycolmap.logging.info("Setting prior cameras from GT")
604
605 with pycolmap.Database.open(str(database_path)) as database:
606 images_gt_by_name = {}
607 for image_gt in camera_priors_sparse_gt.images.values():
608 images_gt_by_name[image_gt.name] = image_gt
609
610 updated_camera_ids = set()
611 for image in database.read_all_images():
612 if image.name not in images_gt_by_name:
613 pycolmap.logging.warning(
614 f"Not setting prior camera for image {image.name}, "
615 "because it does not exist in GT"
616 )
617 continue
618 image_gt = images_gt_by_name[image.name]
619 if image.camera_id in updated_camera_ids:
620 continue
621 camera_gt = camera_priors_sparse_gt.cameras[image_gt.camera_id]
622 camera_gt.camera_id = image.camera_id
623 camera_gt.has_prior_focal_length = True
624 database.update_camera(camera_gt)
625 updated_camera_ids.add(image.camera_id)
626
627
628 def colmap_reconstruction(
629 args: argparse.Namespace,
630 workspace_path: Path,
631 image_path: Path,
632 camera_priors_sparse_gt: pycolmap.Reconstruction | None = None,
633 covisibility_sparse_gt: pycolmap.Reconstruction | None = None,
634 colmap_extra_args: list | None = None,
635 num_threads: int = 1,
636 gpu_index: str = "-1",
637 phase_tracker: _PhaseTracker | None = None,
638 ) -> None:
639 phase_tracker = phase_tracker or _PhaseTracker()
640 workspace_path.mkdir(parents=True, exist_ok=True)
641
642 database_path = workspace_path / "database.db"
643 if args.overwrite_database and database_path.exists():
644 database_path.unlink()
645
646 sparse_path = workspace_path / "sparse"
647 if args.overwrite_reconstruction and sparse_path.exists():
648 shutil.rmtree(sparse_path)
649
650 if sparse_path.exists():
651 pycolmap.logging.info("Skipping reconstruction, as it already exists")
652 return
653
654 # Clearing matches also clears two-view geometries, so there is no need to
655 # clear the latter separately when both flags are set.
656 if args.overwrite_matches:
657 cleaner_type = "matches"
658 elif args.overwrite_two_view_geometries:
659 cleaner_type = "two_view_geometries"
660 else:
661 cleaner_type = None
662 if cleaner_type is not None:
663 subprocess.check_call(
664 [
665 args.colmap_path,
666 "database_cleaner",
667 "--database_path",
668 database_path,
669 "--type",
670 cleaner_type,
671 ],
672 cwd=workspace_path,
673 preexec_fn=(
674 _set_pdeathsig if platform.system() != "Windows" else None
675 ),
676 )
677
678 # TODO: Expose automatic reconstruction through pycolmap bindings instead
679 # of using the command line interface. One blocker for this is that we
680 # currently do not produce CUDA enabled pycolmap packages.
681 colmap_args = [
682 args.colmap_path,
683 "automatic_reconstructor",
684 "--image_path",
685 image_path,
686 "--workspace_path",
687 workspace_path,
688 "--use_gpu",
689 "1" if args.use_gpu else "0",
690 "--gpu_index",
691 gpu_index,
692 "--num_threads",
693 str(num_threads),
694 "--random_seed",
695 str(args.random_seed),
696 "--feature",
697 args.feature,
698 "--mapper",
699 args.mapper,
700 "--quality",
701 args.quality,
702 ]
703
704 phase_tracker.set("extraction")
705 _run_with_log(
706 colmap_args
707 + (colmap_extra_args or [])
708 + [
709 "--extraction",
710 "1",
711 "--matching",
712 "0",
713 "--sparse",
714 "0",
715 "--dense",
716 "0",
717 ],
718 workspace_path / "extraction.log",
719 cwd=workspace_path,
720 )
721
722 if camera_priors_sparse_gt is not None:
723 set_camera_priors(database_path, camera_priors_sparse_gt)
724
725 phase_tracker.set("matching")
726 _run_with_log(
727 colmap_args
728 + (colmap_extra_args or [])
729 + [
730 "--extraction",
731 "0",
732 "--matching",
733 "1",
734 "--sparse",
735 "0",
736 "--dense",
737 "0",
738 ],
739 workspace_path / "matching.log",
740 cwd=workspace_path,
741 )
742
743 if covisibility_sparse_gt is not None:
744 filter_covisibility(
745 database_path,
746 covisibility_sparse_gt,
747 args.covisibility_frustum_near,
748 args.covisibility_frustum_far,
749 args.covisibility_max_viewing_angle,
750 args.covisibility_min_shared_points,
751 )
752
753 # Decouple matching from sparse reconstruction, because matching will
754 # initialize an OpenGL context and Mac on Apple silicon tends to assign GUI
755 # applications to the low efficiency cores but we want to use the
756 # performance cores.
757 phase_tracker.set("reconstruction")
758 _run_with_log(
759 colmap_args
760 + (colmap_extra_args or [])
761 + [
762 "--extraction",
763 "0",
764 "--matching",
765 "0",
766 "--sparse",
767 "1",
768 "--dense",
769 "0",
770 ],
771 workspace_path / "reconstruction.log",
772 cwd=workspace_path,
773 )
774
775
776 def panorama_reconstruction(
777 args: argparse.Namespace,
778 scene_info: SceneInfo,
779 num_threads: int,
780 gpu_index: str,
781 phase_tracker: _PhaseTracker | None = None,
782 ) -> None:
783 """Run the reusable pycolmap panorama pipeline for a benchmark scene."""
784 phase_tracker = phase_tracker or _PhaseTracker()
785 workspace_path = scene_info.workspace_path
786 sparse_path = workspace_path / scene_info.reconstruction_subdir
787
788 if args.overwrite_reconstruction and workspace_path.exists():
789 shutil.rmtree(workspace_path)
790 if sparse_path.exists():
791 pycolmap.logging.info("Skipping reconstruction, as it already exists")
792 return
793 if args.feature != "sift":
794 raise ValueError("Panorama reconstruction currently supports SIFT only")
795 if args.mapper == "hierarchical":
796 raise ValueError(
797 "Panorama reconstruction does not support hierarchical mapping"
798 )
799 if args.uncalibrated:
800 raise ValueError(
801 "Equirectangular panorama reconstruction has fixed calibration"
802 )
803
804 render_type = scene_info.reconstruction_backend.removeprefix("panorama-")
805 if render_type not in {"perspective_overlapping", "spherical"}:
806 raise ValueError(
807 f"Unknown panorama reconstruction backend: "
808 f"{scene_info.reconstruction_backend}"
809 )
810
811 covisibility_path = None
812 min_shared_points = args.covisibility_min_shared_points
813 if (
814 args.filter_covisibility
815 and scene_info.covisibility_path is not None
816 and scene_info.covisibility_path.exists()
817 ):
818 covisibility_path = scene_info.covisibility_path
819 min_shared_points = (
820 scene_info.covisibility_min_shared_points
821 if scene_info.covisibility_min_shared_points is not None
822 else args.covisibility_min_shared_points
823 )
824
825 workspace_path.mkdir(parents=True, exist_ok=True)
826 phase_tracker.set("reconstruction")
827 panorama.reconstruct(
828 scene_info.image_path,
829 workspace_path,
830 panorama.PanoramaReconstructionOptions(
831 matcher=panorama.Matcher.SEQUENTIAL,
832 mapper=panorama.Mapper(args.mapper),
833 render_type=panorama.PanoRenderType(render_type),
834 random_seed=args.random_seed,
835 num_threads=num_threads,
836 gpu_index=gpu_index,
837 use_gpu=args.use_gpu,
838 covisibility_path=covisibility_path,
839 covisibility_min_shared_points=min_shared_points,
840 show_progress=False,
841 ),
842 )
843 sparse_path.mkdir(parents=True, exist_ok=True)
844
845
846 def colmap_alignment(
847 args: argparse.Namespace,
848 sparse_path: Path,
849 sparse_gt_path: Path,
850 sparse_aligned_path: Path,
851 max_ref_model_error: float,
852 ) -> None:
853 if args.overwrite_alignment and sparse_aligned_path.exists():
854 shutil.rmtree(sparse_aligned_path)
855 if sparse_aligned_path.exists():
856 pycolmap.logging.info("Skipping alignment, as it already exists")
857 return
858
859 if sparse_path.exists():
860 sparse_aligned_path.mkdir(parents=True, exist_ok=True)
861 _run_with_log(
862 [
863 args.colmap_path,
864 "model_aligner",
865 "--input_path",
866 sparse_path,
867 "--ref_model_path",
868 sparse_gt_path,
869 "--output_path",
870 sparse_aligned_path,
871 "--alignment_max_error",
872 str(max_ref_model_error),
873 ],
874 sparse_aligned_path.parent / "alignment.log",
875 check=False,
876 )
877
878
879 def merge_sub_models(
880 sub_models: list[pycolmap.Reconstruction],
881 ) -> pycolmap.Reconstruction:
882 """Merge estimated sub-models into a single reconstruction.
883
884 Each sub-model keeps its own (independent) gauge, so sub-models are
885 "randomly" aligned to each other. With this simple approach there is a
886 small chance that images from different sub-models happen to be correctly
887 aligned and the error is therefore underestimated, but this is very
888 unlikely to happen.
889 """
890 sparse_merged = pycolmap.Reconstruction()
891 for sparse in sub_models:
892 for image in sparse.images.values():
893 if image.image_id in sparse_merged.images:
894 continue
895 if image.camera_id not in sparse_merged.cameras:
896 sparse_merged.add_camera(image.camera)
897 if image.frame_id not in sparse_merged.frames:
898 if image.frame.rig_id not in sparse_merged.rigs:
899 sparse_merged.add_rig(image.frame.rig)
900 image.frame.reset_rig_ptr()
901 sparse_merged.add_frame(image.frame)
902 image.reset_camera_ptr()
903 image.reset_frame_ptr()
904 sparse_merged.add_image(image)
905 return sparse_merged
906
907
908 def process_scene(
909 args: argparse.Namespace,
910 scene_info: SceneInfo,
911 dataset: Dataset,
912 num_threads: int,
913 gpu_index: str = "-1",
914 progress_status=None,
915 ) -> SceneResult:
916 pycolmap.logging.info(
917 f"Processing dataset={scene_info.dataset}, "
918 f"category={scene_info.category}, "
919 f"scene={scene_info.scene}"
920 )
921
922 position_accuracy_gt = dataset.position_accuracy_gt
923
924 tracker = _PhaseTracker(progress_status, _scene_key(scene_info))
925
926 tracker.set("setup")
927 dataset.prepare_scene(scene_info)
928
929 sparse_gt = pycolmap.Reconstruction(str(scene_info.sparse_gt_path))
930
931 if scene_info.reconstruction_backend == "automatic":
932 colmap_reconstruction(
933 args=args,
934 workspace_path=scene_info.workspace_path,
935 image_path=scene_info.image_path,
936 camera_priors_sparse_gt=(
937 sparse_gt
938 if not args.uncalibrated and scene_info.has_camera_priors
939 else None
940 ),
941 covisibility_sparse_gt=(
942 sparse_gt
943 if args.filter_covisibility
944 and dataset.supports_covisibility_filtering
945 else None
946 ),
947 num_threads=num_threads,
948 colmap_extra_args=scene_info.colmap_extra_args,
949 gpu_index=gpu_index,
950 phase_tracker=tracker,
951 )
952 else:
953 panorama_reconstruction(
954 args=args,
955 scene_info=scene_info,
956 num_threads=num_threads,
957 gpu_index=gpu_index,
958 phase_tracker=tracker,
959 )
960
961 tracker.set("evaluation")
962
963 # Load all estimated sub-models. Both metrics keep the sub-models separate:
964 # the relative set-based metric forms edges within a sub-model, and the
965 # absolute metric scores each GT image against the best-aligned sub-model.
966 # For absolute errors each sub-model is aligned to the GT independently.
967 # These sub-models are turned into a flat error array via
968 # compute_scene_errors.
969 sub_models: list[pycolmap.Reconstruction] = []
970 num_components = 0
971 largest_component = 0
972 reconstruction_path = (
973 scene_info.workspace_path / scene_info.reconstruction_subdir
974 )
975 for sparse_path in reconstruction_path.iterdir():
976 if not sparse_path.is_dir():
977 continue
978 num_components += 1
979 sparse = None
980 if args.error_type.startswith("relative"):
981 sparse = pycolmap.Reconstruction(str(sparse_path))
982 elif args.error_type.startswith("absolute"):
983 sparse_aligned_path = (
984 scene_info.workspace_path / "sparse_aligned" / sparse_path.name
985 )
986 colmap_alignment(
987 args=args,
988 sparse_path=sparse_path,
989 sparse_gt_path=scene_info.sparse_gt_path,
990 sparse_aligned_path=sparse_aligned_path,
991 max_ref_model_error=position_accuracy_gt,
992 )
993 if (sparse_aligned_path / "images.bin").exists():
994 sparse = pycolmap.Reconstruction(str(sparse_aligned_path))
995 else:
996 raise ValueError(f"Invalid error type: {args.error_type}")
997
998 if sparse is None:
999 continue
1000
1001 largest_component = max(largest_component, sparse.num_images())
1002 sub_models.append(sparse)
1003
1004 # Registered images counted as the union of names across all sub-models,
1005 # restricted to GT images so registered outliers (e.g. IMC2025) are not
1006 # counted and num_reg_images stays consistent with num_images.
1007 gt_image_names = {image.name for image in sparse_gt.images.values()}
1008 num_reg_images = len(
1009 {
1010 image.name
1011 for sub_model in sub_models
1012 for image in sub_model.images.values()
1013 if image.name in gt_image_names
1014 }
1015 )
1016
1017 # The dataset turns the estimated sub-models into a flat error array. The
1018 # default implementation uses the set-based grouped metrics; datasets (e.g.
1019 # IMC2025) can customize the grouping or override the computation entirely.
1020 errors = compute_scene_errors(
1021 args=args,
1022 scene_info=scene_info,
1023 sub_models=sub_models,
1024 sparse_gt=sparse_gt,
1025 position_accuracy_gt=position_accuracy_gt,
1026 )
1027
1028 tracker.set("finished")
1029 return SceneResult(
1030 scene_info=scene_info,
1031 errors=errors,
1032 num_images=sparse_gt.num_images(),
1033 num_reg_images=num_reg_images,
1034 num_components=num_components,
1035 largest_component=largest_component,
1036 )
1037
1038
1039 def _parse_gpu_index(args: argparse.Namespace) -> list[int]:
1040 if args.gpu_index == "-1":
1041 if not pycolmap.has_cuda:
1042 return [-1]
1043 num_devices = pycolmap.get_num_cuda_devices() # type: ignore[attr-defined]
1044 if num_devices <= 0:
1045 return [-1]
1046 return list(range(num_devices))
1047 indices = [int(idx) for idx in args.gpu_index.split(",") if idx.strip()]
1048 return indices if indices else [-1]
1049
1050
1051 def _process_scene_with_gpu(
1052 scene_info_and_gpu: tuple[SceneInfo, str],
1053 args: argparse.Namespace,
1054 dataset: Dataset,
1055 num_threads: int,
1056 progress_status=None,
1057 ) -> SceneResult:
1058 scene_info, gpu_index = scene_info_and_gpu
1059 return process_scene(
1060 args=args,
1061 scene_info=scene_info,
1062 dataset=dataset,
1063 num_threads=num_threads,
1064 gpu_index=gpu_index,
1065 progress_status=progress_status,
1066 )
1067
1068
1069 @functools.cache
1070 def _warn_nondeterministic(seed_flag: str, num_threads_per_scene: int) -> None:
1071 """Warns once per process; process_scenes() runs per dataset and seed."""
1072 pycolmap.logging.warning(
1073 f"{seed_flag} is set but "
1074 f"num_threads_per_scene={num_threads_per_scene} > 1: RANSAC seeds "
1075 "per thread, so results are NOT deterministic. Pass "
1076 "--threads_per_scene 1 for reproducible / paired A-B runs."
1077 )
1078
1079
1080 def process_scenes(
1081 args: argparse.Namespace,
1082 scene_infos: list[SceneInfo],
1083 dataset: Dataset,
1084 ) -> MetricsByCatByScene:
1085 position_accuracy_gt = dataset.position_accuracy_gt
1086 error_thresholds = get_error_thresholds(args)
1087
1088 gpu_index = _parse_gpu_index(args)
1089 scene_gpu_pairs = [
1090 (scene_info, str(gpu_index[i % len(gpu_index)]))
1091 for i, scene_info in enumerate(scene_infos)
1092 ]
1093
1094 num_parallel_scenes = min(args.num_parallel_scenes, len(scene_infos))
1095 if args.threads_per_scene > 0:
1096 num_threads_per_scene = args.threads_per_scene
1097 else:
1098 num_threads_per_scene = max(1, args.num_threads // num_parallel_scenes)
1099 if args.random_seed >= 0 and num_threads_per_scene != 1:
1100 _warn_nondeterministic(args.seed_flag, num_threads_per_scene)
1101
1102 manager = None
1103 progress_status = None
1104 monitor_thread = None
1105 stop_event = threading.Event()
1106 if args.progress:
1107 manager = multiprocessing.Manager()
1108 progress_status = manager.dict()
1109 monitor_thread = threading.Thread(
1110 target=_run_progress_monitor,
1111 args=(progress_status, len(scene_infos), stop_event),
1112 daemon=True,
1113 )
1114 monitor_thread.start()
1115
1116 try:
1117 p = multiprocessing.Pool(
1118 processes=num_parallel_scenes, initializer=_init_pool_worker
1119 )
1120 try:
1121 results = list(
1122 p.imap_unordered(
1123 functools.partial(
1124 _process_scene_with_gpu,
1125 args=args,
1126 dataset=dataset,
1127 num_threads=num_threads_per_scene,
1128 progress_status=progress_status,
1129 ),
1130 scene_gpu_pairs,
1131 chunksize=1,
1132 )
1133 )
1134 except KeyboardInterrupt:
1135 pycolmap.logging.warning(
1136 "Interrupted, terminating workers and child processes..."
1137 )
1138 p.terminate()
1139 raise
1140 except BaseException:
1141 p.terminate()
1142 raise
1143 else:
1144 p.close()
1145 finally:
1146 p.join()
1147 finally:
1148 stop_event.set()
1149 if monitor_thread is not None:
1150 monitor_thread.join()
1151 if manager is not None:
1152 manager.shutdown()
1153
1154 metrics: MetricsByCatByScene = collections.defaultdict(dict)
1155 for result in results:
1156 metrics[result.scene_info.category][result.scene_info.scene] = Metrics(
1157 aucs=compute_auc(
1158 result.errors,
1159 error_thresholds,
1160 min_error=position_accuracy_gt,
1161 ),
1162 recalls=compute_recall(result.errors, error_thresholds),
1163 error_thresholds=error_thresholds,
1164 error_type=args.error_type,
1165 num_images=result.num_images,
1166 num_reg_images=result.num_reg_images,
1167 num_components=result.num_components,
1168 largest_component=result.largest_component,
1169 errors=np.asarray(result.errors),
1170 position_accuracy_gt=position_accuracy_gt,
1171 )
1172
1173 for category in metrics:
1174 metrics[category].update(
1175 aggregate_scene_metrics(
1176 metrics[category].items(),
1177 error_thresholds=error_thresholds,
1178 error_type=args.error_type,
1179 )
1180 )
1181
1182 return metrics
1183
1184
1185 def aggregate_scene_metrics(
1186 scene_metrics: Iterable[tuple[str, Metrics]],
1187 error_thresholds: npt.NDArray[np.floating],
1188 error_type: str,
1189 ) -> dict[str, Metrics]:
1190 """Compute __avg__ (mean of per-scene metrics) and __all__ (recomputed
1191 from the pool of raw errors) summary entries from per-scene Metrics.
1192
1193 Skips entries whose key starts and ends with "__" so this can be applied
1194 iteratively at higher levels (category -> dataset -> overall) without
1195 double-counting previously-emitted summaries.
1196 """
1197 real = [
1198 m
1199 for k, m in scene_metrics
1200 if not (k.startswith("__") and k.endswith("__"))
1201 ]
1202 if not real:
1203 return {}
1204
1205 n = len(real)
1206 sum_num_images = sum(m.num_images for m in real)
1207 sum_num_reg_images = sum(m.num_reg_images for m in real)
1208 sum_num_components = sum(m.num_components for m in real)
1209 sum_largest_component = sum(m.largest_component for m in real)
1210 min_pos_acc = min(m.position_accuracy_gt for m in real)
1211 pooled_errors = np.concatenate([m.errors for m in real])
1212
1213 summary = {
1214 "__avg__": Metrics(
1215 aucs=np.mean([m.aucs for m in real], axis=0),
1216 recalls=np.mean([m.recalls for m in real], axis=0),
1217 error_thresholds=error_thresholds,
1218 error_type=error_type,
1219 num_images=int(round(sum_num_images / n)),
1220 num_reg_images=int(round(sum_num_reg_images / n)),
1221 num_components=int(round(sum_num_components / n)),
1222 largest_component=int(round(sum_largest_component / n)),
1223 position_accuracy_gt=min_pos_acc,
1224 ),
1225 }
1226 if pooled_errors.size:
1227 summary["__all__"] = Metrics(
1228 aucs=compute_auc(
1229 pooled_errors, error_thresholds, min_error=min_pos_acc
1230 ),
1231 recalls=compute_recall(pooled_errors, error_thresholds),
1232 error_thresholds=error_thresholds,
1233 error_type=error_type,
1234 num_images=sum_num_images,
1235 num_reg_images=sum_num_reg_images,
1236 num_components=sum_num_components,
1237 largest_component=sum_largest_component,
1238 errors=pooled_errors,
1239 position_accuracy_gt=min_pos_acc,
1240 )
1241 return summary
1242
1243
1244 def get_error_thresholds(args: argparse.Namespace) -> npt.NDArray[np.floating]:
1245 if args.error_type.startswith("relative"):
1246 return np.array(args.rel_error_thresholds)
1247 elif args.error_type.startswith("absolute"):
1248 return np.array(args.abs_error_thresholds)
1249 else:
1250 raise ValueError(f"Invalid error type: {args.error_type}")
1251
1252
1253 def get_scores(error_type: str, metrics: Metrics) -> npt.NDArray[np.floating]:
1254 if error_type.endswith("auc"):
1255 return metrics.aucs
1256 elif error_type.endswith("recall"):
1257 return metrics.recalls
1258 else:
1259 raise ValueError(f"Invalid error type: {error_type}")
1260
1261
1262 def compute_rel_pose_error(
1263 tgt_from_src_est: pycolmap.Rigid3d,
1264 tgt_from_src_gt: pycolmap.Rigid3d,
1265 min_proj_center_dist: float,
1266 ) -> tuple[float, float]:
1267 """Angular relative pose errors (dt, dR) in degrees.
1268
1269 dR is the geodesic rotation error and dt is the angular distance between
1270 the relative translation directions. If the GT baseline is shorter than
1271 min_proj_center_dist, the translation direction is unstable and dt is set
1272 to zero, so only the rotation error is measured.
1273 """
1274 estimated_from_gt = tgt_from_src_est.inverse() * tgt_from_src_gt
1275
1276 if np.linalg.norm(tgt_from_src_gt.translation) < min_proj_center_dist:
1277 # If the cameras almost coincide, then the angular direction distance
1278 # is unstable, because a small position change can cause a large
1279 # rotational error. In this case, we only measure rotational error.
1280 dt = 0.0
1281 else:
1282 dt = vec_angular_dist_deg(
1283 tgt_from_src_est.translation, tgt_from_src_gt.translation
1284 )
1285
1286 dR = np.rad2deg(estimated_from_gt.rotation.angle())
1287 return dt, dR
1288
1289
1290 def compute_scene_errors(
1291 args: argparse.Namespace,
1292 scene_info: SceneInfo,
1293 sub_models: list[pycolmap.Reconstruction],
1294 sparse_gt: pycolmap.Reconstruction,
1295 position_accuracy_gt: float,
1296 ) -> npt.NDArray[np.floating]:
1297 """Compute the flat error array for a reconstructed scene.
1298
1299 Keeps the estimated sub-models separate and computes the set-based,
1300 GT-component-aware relative or absolute pose errors against the ground
1301 truth. The GT components come from scene_info.image_name_to_component,
1302 defaulting to a single reconstruction (all GT images in component 0) when
1303 the dataset does not provide one. Datasets can populate that mapping (via
1304 list_scenes) to control the grouping.
1305 """
1306 image_name_to_component = scene_info.image_name_to_component or {
1307 image.name: 0 for image in sparse_gt.images.values()
1308 }
1309 if args.error_type.startswith("relative"):
1310 return compute_grouped_rel_errors(
1311 sparse_gt=sparse_gt,
1312 sub_models=sub_models,
1313 image_name_to_component=image_name_to_component,
1314 min_proj_center_dist=position_accuracy_gt,
1315 )
1316 elif args.error_type.startswith("absolute"):
1317 return compute_grouped_abs_errors(
1318 sparse_gt=sparse_gt,
1319 sub_models=sub_models,
1320 image_name_to_component=image_name_to_component,
1321 )
1322 else:
1323 raise ValueError(f"Invalid error type: {args.error_type}")
1324
1325
1326 def compute_grouped_rel_errors(
1327 sparse_gt: pycolmap.Reconstruction,
1328 sub_models: list[pycolmap.Reconstruction],
1329 image_name_to_component: dict[str, int],
1330 min_proj_center_dist: float,
1331 ) -> npt.NDArray[np.floating]:
1332 """Set-based relative pose errors over the graph of image pairs.
1333
1334 Let A be the set of ordered image pairs (i, j) that share an estimated
1335 sub-model and B the set of ordered pairs that share a GT component (as
1336 defined by image_name_to_component). For pairs in A n B we measure the
1337 relative pose error; for pairs in the symmetric difference (grouped in only
1338 one of the two, i.e. wrong merges / registered outliers or failed /
1339 fragmented registrations) we assign the maximum error of 180 degrees. The
1340 returned error array covers all pairs in A u B.
1341
1342 A and B are materialized as flat collections and scored in a single pass.
1343 A is a multiset (tgt_from_src_est_edges): an image may appear in several
1344 sub-models, so the same edge can carry several estimated relative poses,
1345 each contributing one error entry.
1346 """
1347 gt_cam_from_world = {
1348 image.name: image.cam_from_world()
1349 for image in sparse_gt.images.values()
1350 }
1351
1352 # A: ordered estimated edges -> list of relative poses (one per sub-model
1353 # containing both endpoints). Keeping a list makes A a multiset.
1354 tgt_from_src_est_edges: dict[tuple[str, str], list[pycolmap.Rigid3d]] = (
1355 collections.defaultdict(list)
1356 )
1357 for sub_model in sub_models:
1358 cam_from_world = {
1359 image.name: image.cam_from_world()
1360 for image in sub_model.images.values()
1361 }
1362 for src_name, tgt_name in itertools.permutations(cam_from_world, 2):
1363 tgt_from_src_est = (
1364 cam_from_world[tgt_name] * cam_from_world[src_name].inverse()
1365 )
1366 tgt_from_src_est_edges[(src_name, tgt_name)].append(
1367 tgt_from_src_est
1368 )
1369
1370 # B: ordered GT edges grouped by GT component. Outliers never belong to a
1371 # GT component, and names absent from sparse_gt cannot form a measurable GT
1372 # edge, so both are excluded here.
1373 names_by_component: dict[int, list[str]] = collections.defaultdict(list)
1374 for name, component in image_name_to_component.items():
1375 if component == OUTLIER_COMPONENT_ID or name not in gt_cam_from_world:
1376 continue
1377 names_by_component[component].append(name)
1378 gt_edges: set[tuple[str, str]] = set()
1379 for group_names in names_by_component.values():
1380 gt_edges.update(itertools.permutations(group_names, 2))
1381
1382 errors: list[float] = []
1383 for edge in set(tgt_from_src_est_edges) | gt_edges:
1384 src_name, tgt_name = edge
1385 tgt_from_src_ests = tgt_from_src_est_edges.get(edge, [])
1386 if edge in gt_edges:
1387 tgt_from_src_gt = (
1388 gt_cam_from_world[tgt_name]
1389 * gt_cam_from_world[src_name].inverse()
1390 )
1391 if not tgt_from_src_ests:
1392 # Edge in B - A: failed / fragmented registration.
1393 errors.append(180.0)
1394 for tgt_from_src_est in tgt_from_src_ests:
1395 # Edge in A n B: measure the relative pose error.
1396 dt, dR = compute_rel_pose_error(
1397 tgt_from_src_est, tgt_from_src_gt, min_proj_center_dist
1398 )
1399 errors.append(max(dt, dR))
1400 else:
1401 # Edge in A - B: wrong merge or registered outlier.
1402 errors.extend(180.0 for _ in tgt_from_src_ests)
1403
1404 if not errors:
1405 # No evaluable pairs (e.g. only singleton GT reconstructions). Report
1406 # the worst case rather than raising downstream on an empty array.
1407 return np.array([180.0])
1408 return np.array(errors)
1409
1410
1411 def compute_abs_errors(
1412 sparse_gt: pycolmap.Reconstruction,
1413 sparse: pycolmap.Reconstruction,
1414 image_name_to_component: dict[str, int] | None = None,
1415 ) -> tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]]:
1416 """Computes rotational and translational absolute pose errors.
1417
1418 Assumes that the input reconstructions are aligned in the same coordinate
1419 system. Iterates over the estimated reconstruction (sparse) and computes one
1420 error per sparse image that also exists in the ground truth, in
1421 sparse.images.values() order; sparse images absent from the GT are skipped.
1422
1423 When image_name_to_component is given, the reconstruction is treated as
1424 covering a single GT component: the component with the smallest mean finite
1425 translational error is kept intact and every other image (other components,
1426 outliers, or images missing from the mapping) is set to the maximum error
1427 (inf translation, 180 rotation). Without the mapping the raw per-image
1428 errors are returned.
1429 """
1430
1431 if sparse is None:
1432 pycolmap.logging.error("Reconstruction or alignment failed")
1433 return (
1434 np.array([], dtype=np.float64),
1435 np.array([], dtype=np.float64),
1436 )
1437
1438 gt_images = {image.name: image for image in sparse_gt.images.values()}
1439
1440 names: list[str] = []
1441 dt_list: list[float] = []
1442 dR_list: list[float] = []
1443 for image in sparse.images.values():
1444 image_gt = gt_images.get(image.name)
1445 if image_gt is None:
1446 continue
1447
1448 estimated_from_gt = (
1449 image.cam_from_world() * image_gt.cam_from_world().inverse()
1450 )
1451
1452 names.append(image.name)
1453 dt_list.append(float(np.linalg.norm(estimated_from_gt.translation)))
1454 dR_list.append(float(np.rad2deg(estimated_from_gt.rotation.angle())))
1455
1456 dts = np.array(dt_list, dtype=np.float64)
1457 dRs = np.array(dR_list, dtype=np.float64)
1458
1459 if image_name_to_component is None:
1460 return dts, dRs
1461
1462 best_component = _best_component(names, dts, image_name_to_component)
1463
1464 # Keep only the best component intact; max out every other image (other
1465 # components, outliers, or names missing from the mapping). When no
1466 # component is selectable (best_component is None) every image is maxed out.
1467 for i, name in enumerate(names):
1468 in_best_component = (
1469 best_component is not None
1470 and image_name_to_component.get(name) == best_component
1471 )
1472 if not in_best_component:
1473 dts[i] = np.inf
1474 dRs[i] = 180
1475
1476 return dts, dRs
1477
1478
1479 def _best_component(
1480 names: list[str],
1481 dts: npt.NDArray[np.floating],
1482 image_name_to_component: dict[str, int],
1483 ) -> int | None:
1484 """GT component id with the smallest mean finite translational error.
1485
1486 Returns None when no image maps to a selectable component. Outliers and
1487 names missing from the mapping never form a selectable component.
1488 """
1489 finite_dts_by_component: dict[int, list[float]] = collections.defaultdict(
1490 list
1491 )
1492 for name, dt in zip(names, dts, strict=True):
1493 component = image_name_to_component.get(name)
1494 if (
1495 component is not None
1496 and component != OUTLIER_COMPONENT_ID
1497 and np.isfinite(dt)
1498 ):
1499 finite_dts_by_component[component].append(float(dt))
1500 if not finite_dts_by_component:
1501 return None
1502 return min(
1503 finite_dts_by_component,
1504 key=lambda component: float(
1505 np.mean(finite_dts_by_component[component])
1506 ),
1507 )
1508
1509
1510 def compute_grouped_abs_errors(
1511 sparse_gt: pycolmap.Reconstruction,
1512 sub_models: list[pycolmap.Reconstruction],
1513 image_name_to_component: dict[str, int],
1514 ) -> npt.NDArray[np.floating]:
1515 """GT-component-aware absolute pose errors.
1516
1517 Each estimated sub-model is assumed to be aligned to the GT. A GT image
1518 that is registered in n sub-models contributes n (translational) errors,
1519 one per reconstruction; a GT image registered in no sub-model contributes a
1520 single infinite error (a failure). Within each sub-model only its
1521 best-matching GT component (smallest mean finite error) is kept intact and
1522 every other GT image is maxed out (see compute_abs_errors). Because the
1523 selection is per sub-model, a scene with several GT components can credit
1524 several of them, one per sub-model. With a single component this reduces to
1525 the standard absolute metric.
1526 """
1527 gt_names = [image.name for image in sparse_gt.images.values()]
1528 gt_name_set = set(gt_names)
1529
1530 # Flat node multiset keyed by GT image name: one translational error per
1531 # (GT image, sub-model) registration. compute_abs_errors keeps each
1532 # sub-model's best GT component intact and maxes out (inf) every other
1533 # registered image, which still contributes an error. Its returned errors
1534 # are aligned to the sub-model's images that also exist in the GT, in
1535 # sub_model.images.values() order, so we rebuild the names with the same
1536 # filter/order.
1537 errors_by_name: dict[str, list[float]] = collections.defaultdict(list)
1538 for sub_model in sub_models:
1539 sub_dts, _ = compute_abs_errors(
1540 sparse_gt=sparse_gt,
1541 sparse=sub_model,
1542 image_name_to_component=image_name_to_component,
1543 )
1544 sub_names = [
1545 image.name
1546 for image in sub_model.images.values()
1547 if image.name in gt_name_set
1548 ]
1549 for name, dt in zip(sub_names, sub_dts, strict=True):
1550 errors_by_name[name].append(float(dt))
1551
1552 # A GT image registered in no sub-model counts as a single failure.
1553 for name in gt_names:
1554 if not errors_by_name[name]:
1555 errors_by_name[name].append(np.inf)
1556
1557 # Flatten the node dict in GT image order.
1558 return np.array([dt for name in gt_names for dt in errors_by_name[name]])
1559
1560
1561 def compute_auc(
1562 errors: npt.NDArray[np.floating],
1563 thresholds: npt.NDArray[np.floating],
1564 min_error: float = 0,
1565 ) -> npt.NDArray[np.floating]:
1566 num_elems = len(errors)
1567 if len(errors) == 0:
1568 raise ValueError("No errors to evaluate")
1569
1570 errors = np.sort(errors)
1571 recalls = (np.arange(num_elems) + 1) / num_elems
1572
1573 if min_error > 0:
1574 min_index = np.searchsorted(errors, min_error, side="right")
1575 min_recall = min_index / num_elems
1576 recalls = np.r_[min_recall, min_recall, recalls[min_index:]]
1577 errors = np.r_[0, min_error, errors[min_index:]]
1578 else:
1579 recalls = np.r_[0, recalls]
1580 errors = np.r_[0, errors]
1581
1582 aucs = np.zeros(len(thresholds), dtype=np.float64)
1583 for i, t in enumerate(thresholds):
1584 last_index = np.searchsorted(errors, t, side="right")
1585 r = np.r_[recalls[:last_index], recalls[last_index - 1]]
1586 e = np.r_[errors[:last_index], t]
1587 auc = np.trapezoid(r, x=e) / t
1588 aucs[i] = auc * 100
1589
1590 return aucs
1591
1592
1593 def compute_recall(
1594 errors: npt.NDArray[np.floating],
1595 thresholds: npt.NDArray[np.floating],
1596 min_error: float = 0,
1597 ) -> npt.NDArray[np.floating]:
1598 num_elems = len(errors)
1599 if num_elems == 0:
1600 raise ValueError("No errors to evaluate")
1601
1602 recalls = np.zeros(len(thresholds), dtype=np.float64)
1603 for i, t in enumerate(thresholds):
1604 recalls[i] = 100 * np.sum(errors <= t) / num_elems
1605
1606 return recalls
1607
1608
1609 def compute_avg_metrics(
1610 scene_metrics: MetricsByScene,
1611 ) -> tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]]:
1612 auc_sum = None
1613 recall_sum = None
1614 num_scenes = 0
1615 for scene, metrics in scene_metrics.items():
1616 if scene.startswith("__") and scene.endswith("__"):
1617 continue
1618 num_scenes += 1
1619 if auc_sum is None:
1620 auc_sum = copy.copy(metrics.aucs)
1621 if recall_sum is None:
1622 recall_sum = copy.copy(metrics.recalls)
1623 else:
1624 for i in range(len(auc_sum)):
1625 auc_sum[i] += metrics.aucs[i]
1626 for i in range(len(recall_sum)):
1627 recall_sum[i] += metrics.recalls[i]
1628 return np.array(auc_sum) / num_scenes, np.array(recall_sum) / num_scenes
1629
1630
1631 def diff_metrics(
1632 metrics_a: MetricsByDatasetByCatByScene,
1633 metrics_b: MetricsByDatasetByCatByScene,
1634 ):
1635 """Computes difference between two sets of metrics.
1636
1637 Raises exception if the metrics are inconsistent.
1638 """
1639 metrics_diff = copy.deepcopy(metrics_a)
1640 for dataset, category_metrics_a in metrics_a.items():
1641 if dataset not in metrics_b:
1642 raise ValueError(f"Dataset {dataset} not found in metrics_b")
1643 category_metrics_b = metrics_b[dataset]
1644 for category, scene_metrics_a in category_metrics_a.items():
1645 if category not in category_metrics_b:
1646 raise ValueError(f"Category {category} not found in metrics_b")
1647 scene_metrics_b = category_metrics_b[category]
1648 for scene, metrics_a_item in scene_metrics_a.items():
1649 if scene not in scene_metrics_b:
1650 raise ValueError(f"Scene {scene} not found in metrics_b")
1651 metrics_b_item = scene_metrics_b[scene]
1652 if (
1653 metrics_a_item.error_type != metrics_b_item.error_type
1654 or not np.all(
1655 metrics_a_item.error_thresholds
1656 == metrics_b_item.error_thresholds
1657 )
1658 ):
1659 raise ValueError("Inconsistent error thresholds or types")
1660 metrics_diff[dataset][category][scene] = Metrics(
1661 aucs=metrics_a_item.aucs - metrics_b_item.aucs,
1662 recalls=metrics_a_item.recalls - metrics_b_item.recalls,
1663 error_thresholds=metrics_a_item.error_thresholds,
1664 error_type=metrics_a_item.error_type,
1665 num_images=metrics_a_item.num_images
1666 - metrics_b_item.num_images,
1667 num_reg_images=metrics_a_item.num_reg_images
1668 - metrics_b_item.num_reg_images,
1669 num_components=metrics_a_item.num_components
1670 - metrics_b_item.num_components,
1671 largest_component=metrics_a_item.largest_component
1672 - metrics_b_item.largest_component,
1673 )
1674 return metrics_diff
1675
1676
1677 def _is_summary_scene(scene: str) -> bool:
1678 """Whether a scene name is an aggregate row (e.g. __avg__, __all__)."""
1679 return scene.startswith("__") and scene.endswith("__")
1680
1681
1682 def create_result_table(
1683 dataset_metrics: MetricsByDatasetByCatByScene,
1684 ) -> str:
1685 first_metrics = next(
1686 iter(next(iter(next(iter(dataset_metrics.values())).values())).values())
1687 )
1688
1689 is_auc = first_metrics.error_type.endswith("auc")
1690 is_relative = first_metrics.error_type.startswith("relative")
1691 score_type = "AUC" if is_auc else "Recall"
1692 score_unit = "deg" if is_relative else "cm"
1693 label = f"{score_type} @ X {score_unit} (%)"
1694 if is_relative:
1695 thresholds = first_metrics.error_thresholds
1696 else:
1697 thresholds = 100 * first_metrics.error_thresholds # cm
1698
1699 column = "scenes"
1700 size_scenes = max(
1701 len(column) + 2,
1702 max(
1703 len(s)
1704 for d in dataset_metrics.values()
1705 for c in d.values()
1706 for s in c
1707 ),
1708 )
1709 size_aucs = max(len(label) + 2, len(thresholds) * 7 - 1)
1710 size_imgs = 12
1711 size_comps = 12
1712 size_sep = size_scenes + size_aucs + size_imgs + size_comps + 3
1713 header = (
1714 f"{column:=^{size_scenes}} {label:=^{size_aucs}} "
1715 f"{'images':=^{size_imgs}} {'components':=^{size_comps}}"
1716 )
1717 header += "\n" + " " * (size_scenes + 1)
1718 header += " ".join(f"{str(t).rstrip('.'):^6}" for t in thresholds)
1719 header += " reg all num largest"
1720 text = [header]
1721
1722 def render_block(
1723 header_text: str,
1724 scene_metrics: MetricsByScene,
1725 header_fill: str = "=",
1726 ) -> None:
1727 text.append(f"\n{header_text:{header_fill}^{size_sep}}")
1728 any_scene_row = False
1729 summary_separator_drawn = False
1730 for scene, metrics in sorted(
1731 scene_metrics.items(),
1732 key=lambda x: (
1733 x[0].startswith("__"),
1734 x[0],
1735 ),
1736 ):
1737 scores = get_scores(first_metrics.error_type, metrics)
1738 assert len(scores) == len(thresholds)
1739 row = ""
1740 is_summary = _is_summary_scene(scene)
1741 if is_summary and any_scene_row and not summary_separator_drawn:
1742 row += "-" * size_sep + "\n"
1743 summary_separator_drawn = True
1744 if not is_summary:
1745 any_scene_row = True
1746 if scene == "__avg__":
1747 scene = "average"
1748 if scene == "__all__":
1749 scene = "overall"
1750 row += f"{scene:<{size_scenes}} "
1751 row += " ".join(f"{score:>6.2f}" for score in scores)
1752 row += f" {metrics.num_reg_images:6d}"
1753 row += f"{metrics.num_images:6d}"
1754 row += f" {metrics.num_components:4d}"
1755 row += f"{metrics.largest_component:8d}"
1756 text.append(row)
1757
1758 overall_scene_metrics: list[tuple[str, Metrics]] = []
1759 for dataset, category_metrics in dataset_metrics.items():
1760 dataset_scene_metrics: list[tuple[str, Metrics]] = []
1761 for category, scene_metrics in category_metrics.items():
1762 render_block(f"{dataset}={category}", scene_metrics)
1763 dataset_scene_metrics.extend(scene_metrics.items())
1764 if len(category_metrics) > 1:
1765 render_block(
1766 dataset,
1767 aggregate_scene_metrics(
1768 dataset_scene_metrics,
1769 error_thresholds=first_metrics.error_thresholds,
1770 error_type=first_metrics.error_type,
1771 ),
1772 header_fill="#",
1773 )
1774 overall_scene_metrics.extend(dataset_scene_metrics)
1775
1776 if len(dataset_metrics) > 1:
1777 render_block(
1778 "overall",
1779 aggregate_scene_metrics(
1780 overall_scene_metrics,
1781 error_thresholds=first_metrics.error_thresholds,
1782 error_type=first_metrics.error_type,
1783 ),
1784 header_fill="#",
1785 )
1786
1787 return "\n".join(text)
1788
1789
1790 def load_report(path: Path) -> MetricsByDatasetByCatByScene:
1791 """Loads a report pickled by evaluate.py."""
1792 with open(path, "rb") as report_file:
1793 return pickle.load(report_file)
1794
1795
1796 def _collect_reports(prefix: Path) -> dict[int, Path] | Path:
1797 """Collects the reports of one variant given as a report path prefix.
1798
1799 Returns seed -> path for the <prefix>_s<seed>.pkl reports of a seeded run,
1800 or the single <prefix>.pkl path of an unseeded one.
1801 """
1802 reports: dict[int, Path] = {}
1803 for path in prefix.parent.glob(f"{prefix.name}_s*.pkl"):
1804 seed = path.stem[len(prefix.name) + 2 :]
1805 if seed.isdigit():
1806 reports[int(seed)] = path
1807 if reports:
1808 return reports
1809 path = prefix.with_name(f"{prefix.name}.pkl")
1810 if not path.exists():
1811 raise SystemExit(
1812 f"found neither {prefix.name}_s<seed>.pkl reports nor {path}"
1813 )
1814 return path
1815
1816
1817 def collect_reports(
1818 path: Path | None, prefix: Path | None
1819 ) -> dict[int, Path] | Path:
1820 """Collects one variant's reports from a report path or a path prefix.
1821
1822 Returns the single report path, or seed -> path for the
1823 <prefix>_s<seed>.pkl reports of a seeded run.
1824 """
1825 if path is not None:
1826 if not path.exists():
1827 raise SystemExit(f"no such report: {path}")
1828 return path
1829 assert prefix is not None
1830 return _collect_reports(prefix)
1831
1832
1833 def pair_reports(
1834 reports_a: dict[int, Path] | Path,
1835 reports_b: dict[int, Path] | Path,
1836 labels: Sequence[str] = ("A", "B"),
1837 seeds: list[int] | None = None,
1838 ) -> tuple[list[Path], list[Path], list[int] | None]:
1839 """Pairs up the collected reports of two variants.
1840
1841 Seeded variants are matched on the seeds they have in common; pass seeds
1842 to restrict the comparison to a subset. A variant that is a single report
1843 is compared against every seed of the other.
1844 """
1845 label_a, label_b = labels
1846
1847 if isinstance(reports_a, dict) and isinstance(reports_b, dict):
1848 # Both seeded: pair them up on the seeds they have in common.
1849 shared = sorted(set(reports_a) & set(reports_b))
1850 if not shared:
1851 raise SystemExit(
1852 f"{label_a} and {label_b} share no seed, but the "
1853 "comparison is paired per seed "
1854 f"({label_a}: {sorted(reports_a)}, "
1855 f"{label_b}: {sorted(reports_b)})"
1856 )
1857 for label, reports in ((label_a, reports_a), (label_b, reports_b)):
1858 dropped = sorted(set(reports) - set(shared))
1859 if dropped:
1860 pycolmap.logging.warning(
1861 f"ignoring {len(dropped)} of {label}'s "
1862 f"{len(reports)} reports, seed(s) {dropped}: the other "
1863 "variant has no report for them"
1864 )
1865 elif isinstance(reports_a, dict):
1866 # Only A seeded: B is a single run, compared against each of A's seeds.
1867 shared = sorted(reports_a)
1868 elif isinstance(reports_b, dict):
1869 shared = sorted(reports_b)
1870 else:
1871 # Neither seeded: a plain one-to-one comparison.
1872 return [reports_a], [reports_b], None
1873
1874 if seeds is not None:
1875 unknown = sorted(set(seeds) - set(shared))
1876 if unknown:
1877 pycolmap.logging.warning(
1878 f"skipping seed(s) {unknown}: not present for both variants"
1879 )
1880 shared = [seed for seed in shared if seed in set(seeds)]
1881 if not shared:
1882 raise SystemExit(f"none of the seeds {seeds} is available")
1883
1884 def paths(reports: dict[int, Path] | Path) -> list[Path]:
1885 if isinstance(reports, Path):
1886 return [reports] * len(shared)
1887 return [reports[seed] for seed in shared]
1888
1889 return paths(reports_a), paths(reports_b), shared
1890
1891
1892 def _first_metrics(report: MetricsByDatasetByCatByScene) -> Metrics:
1893 return next(iter(next(iter(next(iter(report.values())).values())).values()))
1894
1895
1896 def _common_scene_keys(
1897 reports: list[MetricsByDatasetByCatByScene],
1898 ) -> list[SceneKey]:
1899 """Scene keys present in every report, ordered as in the first report."""
1900 key_sets: list[set[SceneKey]] = []
1901 for report in reports:
1902 keys: set[SceneKey] = set()
1903 for dataset, cat_metrics in report.items():
1904 for category, scene_metrics in cat_metrics.items():
1905 for scene in scene_metrics:
1906 keys.add((dataset, category, scene))
1907 key_sets.append(keys)
1908 shared: set[SceneKey] = set()
1909 if key_sets:
1910 shared = key_sets[0].intersection(*key_sets[1:])
1911 ordered: list[SceneKey] = []
1912 for dataset, cat_metrics in reports[0].items():
1913 for category, scene_metrics in cat_metrics.items():
1914 for scene in scene_metrics:
1915 if (dataset, category, scene) in shared:
1916 ordered.append((dataset, category, scene))
1917 return ordered
1918
1919
1920 def _stack_scores(
1921 reports: list[MetricsByDatasetByCatByScene],
1922 key: SceneKey,
1923 error_type: str,
1924 ) -> npt.NDArray[np.floating]:
1925 """Scores for one scene across reports, shaped (num_reports, num_thr)."""
1926 dataset, category, scene = key
1927 return np.array(
1928 [
1929 get_scores(error_type, report[dataset][category][scene])
1930 for report in reports
1931 ]
1932 )
1933
1934
1935 def _render_meanstd(
1936 title: str,
1937 per_key_stack: dict[SceneKey, npt.NDArray[np.floating]],
1938 keys: list[SceneKey],
1939 error_type: str,
1940 thresholds: npt.NDArray[np.floating],
1941 num_runs: int,
1942 signed: bool = False,
1943 num_reported: int | None = None,
1944 ) -> str:
1945 """Renders one mean +/- std table over runs, per scene x threshold.
1946
1947 per_key_stack maps each key to a (num_runs, num_thresholds) score array.
1948 num_reported is shown in the trailing N column as the number of distinct
1949 runs behind the statistics, which is 1 for a single run compared against
1950 every seed of the other variant, and whose std is then zero.
1951 """
1952 is_relative = error_type.startswith("relative")
1953 thresholds_disp = thresholds if is_relative else 100 * thresholds
1954 size_scene = max(8, max(len(s) for _, _, s in keys))
1955 size_cell = 12 # "+dd.dd±dd.dd"
1956 fmt = "{:+6.2f}±{:5.2f}" if signed else "{:6.2f}±{:5.2f}"
1957 header = f"{'scene':<{size_scene}} {'N':>3} " + " ".join(
1958 f"{'@' + str(t).rstrip('.'):^{size_cell}}" for t in thresholds_disp
1959 )
1960 num_reported = num_runs if num_reported is None else num_reported
1961 lines: list[str] = [title, header, "-" * len(header)]
1962 prev_summary = False
1963 for key in sorted(keys, key=lambda k: (_is_summary_scene(k[2]), k)):
1964 scene = key[2]
1965 if _is_summary_scene(scene) and not prev_summary:
1966 lines.append("-" * len(header))
1967 prev_summary = True
1968 scores = per_key_stack[key] # (num_runs, num_thresholds)
1969 mean = scores.mean(axis=0)
1970 std = (
1971 scores.std(axis=0, ddof=1) if num_runs > 1 else np.zeros_like(mean)
1972 )
1973 label = {"__avg__": "average", "__all__": "overall"}.get(scene, scene)
1974 cells = " ".join(
1975 fmt.format(m, s) for m, s in zip(mean, std, strict=True)
1976 )
1977 lines.append(f"{label:<{size_scene}} {num_reported:>3} {cells}")
1978 return "\n".join(lines)
1979
1980
1981 def compare_reports(
1982 report_a_paths: list[Path],
1983 report_b_paths: list[Path],
1984 labels: Sequence[str] = ("A", "B"),
1985 seeds: list[int] | None = None,
1986 ) -> None:
1987 """Logs an A vs B comparison of two sets of paired reports.
1988
1989 With one report per variant this prints the usual result tables for A, B
1990 and A - B. With several reports per variant (one per seed, paired by
1991 position) it instead prints mean +/- std over the runs, with A - B computed
1992 per seed before averaging.
1993 """
1994 if len(report_a_paths) != len(report_b_paths):
1995 raise SystemExit(
1996 "A and B must have the same number of reports (paired by seed): "
1997 f"{len(report_a_paths)} vs {len(report_b_paths)}"
1998 )
1999 num_runs = len(report_a_paths)
2000 if num_runs == 0:
2001 raise SystemExit("no reports to compare")
2002 if seeds is not None and len(seeds) != num_runs:
2003 raise SystemExit(
2004 f"seed count ({len(seeds)}) != report count ({num_runs})"
2005 )
2006 label_a, label_b = labels
2007
2008 reports_a = [load_report(path) for path in report_a_paths]
2009 reports_b = [load_report(path) for path in report_b_paths]
2010
2011 if num_runs == 1:
2012 metrics_a, metrics_b = reports_a[0], reports_b[0]
2013 metrics_diff = diff_metrics(metrics_a, metrics_b)
2014 pycolmap.logging.info(
2015 f"Results {label_a}:\n" + create_result_table(metrics_a)
2016 )
2017 pycolmap.logging.info(
2018 f"Results {label_b}:\n" + create_result_table(metrics_b)
2019 )
2020 pycolmap.logging.info(
2021 f"Results {label_a} - {label_b}:\n"
2022 + create_result_table(metrics_diff)
2023 )
2024 return
2025
2026 keys = _common_scene_keys(reports_a + reports_b)
2027 if not keys:
2028 raise SystemExit("No scenes shared across all reports.")
2029
2030 first_metrics = _first_metrics(reports_a[0])
2031 error_type = first_metrics.error_type
2032 thresholds = np.asarray(first_metrics.error_thresholds)
2033 score = "AUC" if error_type.endswith("auc") else "Recall"
2034
2035 # A variant may be a single run compared against every seed of the other,
2036 # in which case it has no spread of its own and is labelled as such.
2037 single_a = len(set(report_a_paths)) == 1 and num_runs > 1
2038 single_b = len(set(report_b_paths)) == 1 and num_runs > 1
2039 # Both variants ran on the same seeds, so the difference is paired; a
2040 # single run broadcast against the other's seeds is not.
2041 shared = not (single_a or single_b)
2042 over_seeds = f"{score} mean ± std over {num_runs} seeds"
2043
2044 seeds_label = " ".join(map(str, seeds)) if seeds is not None else "-"
2045 num_scenes = len([k for k in keys if not _is_summary_scene(k[2])])
2046 num_reconstructions = num_runs * (2 - single_a - single_b)
2047 pycolmap.logging.info(
2048 f"{label_a} vs {label_b}: {num_runs} seeds; "
2049 f"{num_reconstructions} reconstruction runs over {num_scenes} scenes; "
2050 f"seeds: [{seeds_label}]"
2051 )
2052 if single_a or single_b:
2053 single, seeded = (label_a, label_b) if single_a else (label_b, label_a)
2054 pycolmap.logging.warning(
2055 f"{single} is a single run compared against every seed of "
2056 f"{seeded}: the difference therefore carries only {seeded}'s "
2057 f"spread, and is not a paired (common random number) comparison. "
2058 f"Run {single} on the same seeds for that."
2059 )
2060
2061 stacks_a = {k: _stack_scores(reports_a, k, error_type) for k in keys}
2062 stacks_b = {k: _stack_scores(reports_b, k, error_type) for k in keys}
2063 stacks_diff = {k: stacks_a[k] - stacks_b[k] for k in keys}
2064
2065 common = (keys, error_type, thresholds, num_runs)
2066 pycolmap.logging.info(
2067 "\n"
2068 + _render_meanstd(
2069 f"A = {label_a} "
2070 + (f"({score}, single run)" if single_a else f"({over_seeds})"),
2071 stacks_a,
2072 *common,
2073 num_reported=1 if single_a else num_runs,
2074 )
2075 )
2076 pycolmap.logging.info(
2077 "\n"
2078 + _render_meanstd(
2079 f"B = {label_b} "
2080 + (f"({score}, single run)" if single_b else f"({over_seeds})"),
2081 stacks_b,
2082 *common,
2083 num_reported=1 if single_b else num_runs,
2084 )
2085 )
2086 pycolmap.logging.info(
2087 "\n"
2088 + _render_meanstd(
2089 f"A - B = {label_a} - {label_b} ({over_seeds}, "
2090 + (
2091 "shared seeds -> paired)"
2092 if shared
2093 else f"seeds NOT shared -> {label_b if single_a else label_a}"
2094 "'s spread only)"
2095 ),
2096 stacks_diff,
2097 *common,
2098 signed=True,
2099 )
2100 )