eduzrh Claude Opus 4.7 commited on
Commit
bcb16da
·
1 Parent(s): 88ef1f4

feat: STEM benchmark initial release

Browse files

- Complete benchmark specification document (618 lines)
- 3dSAGER pipeline adapted for spatio-temporal 3D entity matching
- Baseline experiment results on The Hague dataset (155K buildings)
- Disaster simulation + RANSAC alignment working end-to-end
- XGBoost F1=0.998 under CRS rotation 184° + 80% damage

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

.gitattributes CHANGED
@@ -58,3 +58,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ # Git LFS for large data files
62
+ *.joblib filter=lfs diff=lfs merge=lfs -text
63
+ *.pkl filter=lfs diff=lfs merge=lfs -text
64
+ *.json filter=lfs diff=lfs merge=lfs -text
65
+ *.pdf filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories:
4
+ - entity-matching
5
+ - entity-resolution
6
+ language:
7
+ - en
8
+ tags:
9
+ - 3d-entity-matching
10
+ - spatio-temporal
11
+ - entity-resolution
12
+ - cityjson
13
+ - citygml
14
+ - building-matching
15
+ - disaster-response
16
+ - few-shot-learning
17
+ - geospatial
18
+ pretty_name: STEM - Spatio-Temporal 3D Entity Matching Benchmark
19
+ size_categories:
20
+ - 10M-100M
21
+ ---
22
+
23
+ # STEM: Spatio-Temporal 3D Entity Matching Benchmark
24
+
25
+ [![HuggingFace](https://img.shields.io/badge/HuggingFace-STEM-blue)](https://huggingface.co/datasets/eduzrh/STEM)
26
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
27
+
28
+ The **first spatio-temporal 3D entity matching benchmark** for evaluating matching algorithms on 3D building objects across both different data sources and different time points. Designed for both **unsupervised** and **few-shot** entity matching.
29
+
30
+ ## Overview
31
+
32
+ Traditional entity matching operates on tabular records. But real-world geospatial entities — buildings, bridges, infrastructure — are inherently 3D objects. **STEM** enables rigorous evaluation of 3D entity matching under:
33
+
34
+ - **Cross-source** scenarios (different data providers, LOD levels)
35
+ - **Cross-time** scenarios (multi-epoch building inventories)
36
+ - **Post-disaster** scenarios (CRS misalignment + structural damage)
37
+
38
+ ## Quick Start
39
+
40
+ ```bash
41
+ # Clone the repo
42
+ git clone https://huggingface.co/datasets/eduzrh/STEM
43
+ cd STEM
44
+
45
+ # Install dependencies
46
+ pip install -r code/3dSAGER/requirements.txt
47
+
48
+ # Run baseline experiment
49
+ cd code/3dSAGER
50
+ python main.py --dataset_name Hague --evaluation_mode matching --blocking_method bkafi
51
+ ```
52
+
53
+ ## Benchmark Tasks
54
+
55
+ | Task | Description | Difficulty |
56
+ |---|---|---|
57
+ | **Task 1: Cross-Source** | Match buildings across different data providers (same epoch) | Medium |
58
+ | **Task 2: Cross-Time** | Match buildings across different time points (same provider) | Hard |
59
+ | **Task 3: Full ST-EM** | Match across both source AND time + disaster simulation | Very Hard |
60
+
61
+ ## Datasets
62
+
63
+ | Dataset | Buildings | Epochs | Format | Status |
64
+ |---|---|---|---|---|
65
+ | The Hague (3D BAG) | 155,699 | 1 (2 sources) | CityJSON | ✅ Integrated |
66
+ | Lyon Multi-Epoch | ~150K/epoch | 4 (2009-2018) | CityGML | 🔄 In Progress |
67
+
68
+ ## Baseline Results (The Hague, small subset)
69
+
70
+ | Model | Precision | Recall | F1 |
71
+ |---|---|---|---|
72
+ | XGBoost | 0.997 | 1.0 | 0.998 |
73
+ | Random Forest | 0.997 | 1.0 | 0.998 |
74
+ | AdaBoost | 0.991 | 1.0 | 0.995 |
75
+ | MLP | 0.958 | 0.979 | 0.968 |
76
+
77
+ *With disaster simulation (CRS rotation 184° + damage 80%) and RANSAC alignment (rotation error 0.03°)*
78
+
79
+ ## Repository Structure
80
+
81
+ ```
82
+ STEM/
83
+ ├── README.md
84
+ ├── docs/
85
+ │ └── STEM_benchmark_specification.md # Full benchmark specification
86
+ ├── code/
87
+ │ └── 3dSAGER/ # Core pipeline adapted for STEM
88
+ │ ├── main.py
89
+ │ ├── pipelines.py
90
+ │ ├── disaster_simulation.py
91
+ │ ├── alignment.py
92
+ │ └── config.py
93
+ ├── data/
94
+ │ └── hague/ # The Hague baseline data
95
+ ├── experiments/
96
+ │ ├── results/ # Experiment outputs & logs
97
+ │ ├── run_full_pipeline.sh
98
+ │ └── run_experiments.sh
99
+ └── .gitattributes
100
+ ```
101
+
102
+ ## Citation
103
+
104
+ ```bibtex
105
+ @misc{stem2026,
106
+ title={STEM: A Spatio-Temporal 3D Entity Matching Benchmark},
107
+ author={Edu, ZRH},
108
+ year={2026},
109
+ publisher={HuggingFace},
110
+ howpublished={\url{https://huggingface.co/datasets/eduzrh/STEM}}
111
+ }
112
+ ```
113
+
114
+ ## License
115
+
116
+ MIT License — see LICENSE file for details.
code/3dSAGER/alignment.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ alignment.py
3
+
4
+ Two-stage rigid 3D alignment of candidate buildings onto the index coordinate frame.
5
+
6
+ Stage 1 — Estimate transform (Arun et al. 1987):
7
+ Selects high-confidence matched pairs as anchors, estimates rotation R and
8
+ translation t via SVD least-squares, then validates the result by computing
9
+ per-anchor residuals. If the mean residual exceeds the configured threshold
10
+ the alignment is rejected and the pipeline continues with geometric scores only.
11
+
12
+ Stage 2 — Re-score and output:
13
+ Applies (R, t) to all cand centroids and re-scores every pair as:
14
+ final_score = alpha * geometric_score + (1 - alpha) * spatial_score
15
+ where spatial_score = 1 / (1 + distance_after_alignment).
16
+ Then applies (R, t) to all cand geometry and writes an aligned CityJSON file.
17
+
18
+ Reference:
19
+ K. S. Arun, T. S. Huang, and S. D. Blostein. 1987.
20
+ Least-Squares Fitting of Two 3-D Point Sets.
21
+ IEEE TPAMI 9(5):698-700. doi:10.1109/TPAMI.1987.4767965
22
+
23
+ Usage:
24
+ from alignment import RigidAligner
25
+ import config
26
+
27
+ aligner = RigidAligner(config.Alignment, logger=logger)
28
+ rescored_pairs = aligner.run(
29
+ object_dict,
30
+ scored_pairs, # list of (cand_id, index_id, geometric_score)
31
+ suffix="seed1",
32
+ ground_truth_R=simulator.R_crs, # optional, for evaluation only
33
+ ground_truth_t=simulator.t_crs,
34
+ )
35
+ # rescored_pairs: list of (cand_id, index_id, final_score)
36
+ # results/aligned_candidates_seed1.json written if alignment succeeded
37
+ """
38
+
39
+ import json
40
+ import os
41
+ import logging
42
+ import numpy as np
43
+ from typing import List, Tuple, Optional
44
+ import config as cfg
45
+
46
+
47
+ class RigidAligner:
48
+ """
49
+ Estimates a rigid 3D transform from anchor pairs and re-scores all matches.
50
+
51
+ Parameters
52
+ ----------
53
+ align_config : config.Alignment (class reference)
54
+ logger : logging.Logger (optional)
55
+ """
56
+
57
+ def __init__(self, align_config=None, logger=None):
58
+ if align_config is None:
59
+ align_config = cfg.Alignment
60
+ self.enabled = align_config.enabled
61
+ self.min_anchor_pairs = align_config.min_anchor_pairs
62
+ self.confidence_threshold = align_config.confidence_threshold
63
+ self.max_residual_threshold = align_config.max_residual_threshold
64
+ self.alpha = align_config.alpha
65
+ self.output_crs = align_config.output_crs
66
+ self.use_ransac = getattr(align_config, 'use_ransac', True)
67
+ self.ransac_iterations = getattr(align_config, 'ransac_iterations', 1000)
68
+ self.ransac_inlier_threshold = getattr(align_config, 'ransac_inlier_threshold', 10.0)
69
+ self.spatial_sigma = getattr(align_config, 'spatial_sigma', 3.0)
70
+ self.logger = logger or logging.getLogger(__name__)
71
+
72
+ # Set after a successful alignment
73
+ self.R: Optional[np.ndarray] = None
74
+ self.t: Optional[np.ndarray] = None
75
+ self.mean_residual: Optional[float] = None
76
+ self.n_anchors: int = 0
77
+ self.alignment_succeeded: bool = False
78
+
79
+ # ------------------------------------------------------------------ #
80
+ # Public API
81
+ # ------------------------------------------------------------------ #
82
+
83
+ def run(
84
+ self,
85
+ object_dict: dict,
86
+ scored_pairs: List[Tuple[str, str, float]],
87
+ suffix: str = "",
88
+ ground_truth_R: Optional[np.ndarray] = None,
89
+ ground_truth_t: Optional[np.ndarray] = None,
90
+ ) -> List[Tuple[str, str, float]]:
91
+ """
92
+ Full alignment pipeline: estimate transform → validate → re-score → output.
93
+
94
+ Parameters
95
+ ----------
96
+ object_dict : dict
97
+ Full object dict with 'cands' and 'index'.
98
+ scored_pairs : list of (cand_id, index_id, geometric_score)
99
+ All test pairs with their classifier probability scores.
100
+ suffix : str
101
+ Appended to the output filename.
102
+ ground_truth_R, ground_truth_t : np.ndarray, optional
103
+ If provided (from DisasterSimulator), the alignment error is logged
104
+ for evaluation purposes. Not used in the alignment itself.
105
+
106
+ Returns
107
+ -------
108
+ list of (cand_id, index_id, final_score)
109
+ If alignment succeeded: final_score = alpha*geometric + (1-alpha)*spatial.
110
+ If alignment failed/skipped: final_score = geometric_score unchanged.
111
+ """
112
+ if not self.enabled:
113
+ self.logger.info("[RigidAligner] Disabled — returning geometric scores.")
114
+ return scored_pairs
115
+
116
+ # --- Stage 1: Estimate transform ---
117
+ anchors = self._select_anchors(scored_pairs, object_dict)
118
+ self.n_anchors = len(anchors)
119
+
120
+ if self.n_anchors < self.min_anchor_pairs:
121
+ self.logger.warning(
122
+ f"[RigidAligner] Only {self.n_anchors} anchor pairs found "
123
+ f"(need {self.min_anchor_pairs}, threshold={self.confidence_threshold}). "
124
+ f"Skipping alignment — returning geometric scores."
125
+ )
126
+ return scored_pairs
127
+
128
+ P, Q = self._build_point_sets(anchors, object_dict)
129
+ if self.use_ransac:
130
+ R, t, n_inliers, inlier_mask = self._estimate_rigid_transform_ransac(P, Q)
131
+ # Validate using INLIER mean residual when RANSAC found enough inliers.
132
+ # The all-anchor mean is dominated by false-positive anchors (look-alike
133
+ # buildings the classifier scored high) and unfairly rejects a correct
134
+ # transform whenever anchor-pool precision is low.
135
+ if n_inliers >= self.min_anchor_pairs and inlier_mask.any():
136
+ self.mean_residual = self._compute_residual(P[inlier_mask], Q[inlier_mask], R, t)
137
+ all_anchor_mean = self._compute_residual(P, Q, R, t)
138
+ self.logger.info(
139
+ f"[RigidAligner] RANSAC: {self.n_anchors} anchors | "
140
+ f"{n_inliers} inliers | inlier mean residual = {self.mean_residual:.2f} m "
141
+ f"(all-anchor mean = {all_anchor_mean:.2f} m)"
142
+ )
143
+ else:
144
+ self.mean_residual = self._compute_residual(P, Q, R, t)
145
+ self.logger.info(
146
+ f"[RigidAligner] RANSAC: {self.n_anchors} anchors | "
147
+ f"only {n_inliers} inliers (< {self.min_anchor_pairs}) | "
148
+ f"all-anchor mean residual = {self.mean_residual:.2f} m"
149
+ )
150
+ else:
151
+ R, t = self._estimate_rigid_transform(P, Q)
152
+ self.mean_residual = self._compute_residual(P, Q, R, t)
153
+ self.logger.info(
154
+ f"[RigidAligner] {self.n_anchors} anchors | "
155
+ f"mean residual = {self.mean_residual:.2f} m"
156
+ )
157
+
158
+ if self.mean_residual > self.max_residual_threshold:
159
+ self.logger.warning(
160
+ f"[RigidAligner] Mean residual {self.mean_residual:.2f} m exceeds "
161
+ f"threshold {self.max_residual_threshold} m. "
162
+ f"Alignment rejected — returning geometric scores."
163
+ )
164
+ return scored_pairs
165
+
166
+ self.R, self.t = R, t
167
+ self.alignment_succeeded = True
168
+
169
+ # Optional: log error vs ground-truth transform
170
+ if ground_truth_R is not None and ground_truth_t is not None:
171
+ self._log_ground_truth_error(ground_truth_R, ground_truth_t)
172
+
173
+ # --- Stage 2: Re-score using aligned positions ---
174
+ rescored = self._rescore_pairs(scored_pairs, object_dict)
175
+
176
+ # Apply transform to full cand geometry and write output
177
+ self._apply_transform_to_geometry(object_dict['cands'])
178
+ self._write_cityjson(object_dict['cands'], suffix)
179
+
180
+ return rescored
181
+
182
+ # ------------------------------------------------------------------ #
183
+ # Stage 1 helpers
184
+ # ------------------------------------------------------------------ #
185
+
186
+ def _select_anchors(
187
+ self,
188
+ scored_pairs: List[Tuple[str, str, float]],
189
+ object_dict: dict,
190
+ ) -> List[Tuple[str, str]]:
191
+ """Return (cand_id, index_id) pairs with score >= confidence_threshold."""
192
+ cands_keys = set(object_dict['cands'].keys())
193
+ index_keys = set(object_dict['index'].keys())
194
+ return [
195
+ (cid, iid)
196
+ for cid, iid, score in scored_pairs
197
+ if score >= self.confidence_threshold
198
+ and cid in cands_keys
199
+ and iid in index_keys
200
+ ]
201
+
202
+ @staticmethod
203
+ def _build_point_sets(
204
+ anchors: List[Tuple[str, str]],
205
+ object_dict: dict,
206
+ ) -> Tuple[np.ndarray, np.ndarray]:
207
+ """
208
+ Build point sets from anchor centroids.
209
+ P = index centroids (target), Q = cand centroids (source).
210
+ Goal: find R, t such that P_i ≈ R @ Q_i + t.
211
+ """
212
+ P = np.array([object_dict['index'][iid]['centroid'] for _, iid in anchors], dtype=np.float64)
213
+ Q = np.array([object_dict['cands'][cid]['centroid'] for cid, _ in anchors], dtype=np.float64)
214
+ return P, Q
215
+
216
+ @staticmethod
217
+ def _estimate_rigid_transform(
218
+ P: np.ndarray,
219
+ Q: np.ndarray,
220
+ ) -> Tuple[np.ndarray, np.ndarray]:
221
+ """
222
+ Arun et al. 1987 SVD least-squares rigid transform.
223
+
224
+ Returns R (3x3) and t (3,) such that P_i ≈ R @ Q_i + t.
225
+ """
226
+ p_bar = P.mean(axis=0) # (3,)
227
+ q_bar = Q.mean(axis=0) # (3,)
228
+ P_prime = P - p_bar # (N, 3) centered
229
+ Q_prime = Q - q_bar # (N, 3) centered
230
+
231
+ H = Q_prime.T @ P_prime # (3, 3) cross-covariance
232
+ U, _, Vt = np.linalg.svd(H)
233
+ V = Vt.T
234
+
235
+ R = V @ U.T
236
+
237
+ # Fix reflection (degenerate / coplanar case)
238
+ if np.linalg.det(R) < 0:
239
+ V[:, 2] *= -1
240
+ R = V @ U.T
241
+
242
+ t = p_bar - R @ q_bar
243
+ return R, t
244
+
245
+ def _estimate_rigid_transform_ransac(
246
+ self,
247
+ P: np.ndarray,
248
+ Q: np.ndarray,
249
+ ):
250
+ """
251
+ RANSAC-based rigid transform estimation.
252
+
253
+ Each iteration samples 3 anchor pairs, estimates R and t via SVD,
254
+ then counts how many of all anchors are consistent (inliers) under
255
+ that transform. The best transform (most inliers) is refitted on
256
+ all its inliers via SVD for a final least-squares solution.
257
+
258
+ Parameters
259
+ ----------
260
+ P : (N, 3) index centroids
261
+ Q : (N, 3) cand centroids
262
+
263
+ Returns
264
+ -------
265
+ R : (3, 3) rotation matrix
266
+ t : (3,) translation vector
267
+ n_inliers : int
268
+ """
269
+ n = len(P)
270
+ best_inlier_mask = np.zeros(n, dtype=bool)
271
+ best_n_inliers = 0
272
+ best_R, best_t = self._estimate_rigid_transform(P, Q) # fallback
273
+
274
+ rng = np.random.default_rng(42)
275
+
276
+ for _ in range(self.ransac_iterations):
277
+ # Sample 3 unique anchor pairs
278
+ idx = rng.choice(n, size=3, replace=False)
279
+ P_sample, Q_sample = P[idx], Q[idx]
280
+
281
+ # Skip degenerate (collinear) samples
282
+ if np.linalg.matrix_rank(P_sample - P_sample.mean(axis=0)) < 2:
283
+ continue
284
+
285
+ R_cand, t_cand = self._estimate_rigid_transform(P_sample, Q_sample)
286
+
287
+ # Count inliers: anchors whose residual < threshold under this transform
288
+ P_hat = (R_cand @ Q.T).T + t_cand
289
+ residuals = np.linalg.norm(P_hat - P, axis=1)
290
+ inlier_mask = residuals < self.ransac_inlier_threshold
291
+ n_inliers = inlier_mask.sum()
292
+
293
+ if n_inliers > best_n_inliers:
294
+ best_n_inliers = n_inliers
295
+ best_inlier_mask = inlier_mask
296
+ best_R, best_t = R_cand, t_cand
297
+
298
+ # Refit on all inliers of the best solution
299
+ if best_n_inliers >= 3:
300
+ best_R, best_t = self._estimate_rigid_transform(
301
+ P[best_inlier_mask], Q[best_inlier_mask]
302
+ )
303
+ # Recompute inlier mask under the refit transform so it reflects the
304
+ # final R, t rather than the 3-sample one used to score iterations.
305
+ P_hat = (best_R @ Q.T).T + best_t
306
+ residuals = np.linalg.norm(P_hat - P, axis=1)
307
+ best_inlier_mask = residuals < self.ransac_inlier_threshold
308
+ best_n_inliers = int(best_inlier_mask.sum())
309
+ self.logger.info(
310
+ f"[RigidAligner] RANSAC refit on {best_n_inliers}/{n} inliers "
311
+ f"(threshold={self.ransac_inlier_threshold} m, "
312
+ f"iterations={self.ransac_iterations})"
313
+ )
314
+ else:
315
+ self.logger.warning(
316
+ f"[RigidAligner] RANSAC found only {best_n_inliers} inliers — "
317
+ f"falling back to full SVD"
318
+ )
319
+
320
+ return best_R, best_t, best_n_inliers, best_inlier_mask
321
+
322
+ @staticmethod
323
+ def _compute_residual(
324
+ P: np.ndarray,
325
+ Q: np.ndarray,
326
+ R: np.ndarray,
327
+ t: np.ndarray,
328
+ ) -> float:
329
+ """Mean Euclidean residual ||R @ q_i + t - p_i|| over all anchor pairs."""
330
+ P_hat = (R @ Q.T).T + t # (N, 3)
331
+ residuals = np.linalg.norm(P_hat - P, axis=1)
332
+ return float(residuals.mean())
333
+
334
+ def _log_ground_truth_error(
335
+ self,
336
+ gt_R: np.ndarray,
337
+ gt_t: np.ndarray,
338
+ ) -> None:
339
+ """
340
+ Log rotation and translation error vs the ground-truth CRS transform.
341
+
342
+ The disaster simulator applies: cand = R_crs @ original + t_crs
343
+ So the aligner should recover the INVERSE transform:
344
+ self.R ≈ R_crs^T (so that R_crs^T @ R_crs = I)
345
+ self.t ≈ -R_crs^T @ t_crs
346
+
347
+ Rotation check: self.R @ gt_R should be close to I.
348
+ Translation check: self.t should be close to -gt_R^T @ gt_t.
349
+ """
350
+ # Rotation error: R_recovered @ R_gt should equal I if perfect
351
+ R_check = self.R @ gt_R
352
+ angle_err = np.degrees(np.arccos(
353
+ np.clip((np.trace(R_check) - 1.0) / 2.0, -1.0, 1.0)
354
+ ))
355
+ # Translation error: compare recovered t to the expected inverse translation
356
+ expected_t = -gt_R.T @ gt_t
357
+ t_err = np.linalg.norm(self.t - expected_t)
358
+ self.logger.info(
359
+ f"[RigidAligner] Ground-truth comparison: "
360
+ f"rotation error = {angle_err:.2f}°, "
361
+ f"translation error = {t_err:.1f} m"
362
+ )
363
+
364
+ # ------------------------------------------------------------------ #
365
+ # Stage 2 helpers
366
+ # ------------------------------------------------------------------ #
367
+
368
+ def _rescore_pairs(
369
+ self,
370
+ scored_pairs: List[Tuple[str, str, float]],
371
+ object_dict: dict,
372
+ ) -> List[Tuple[str, str, float]]:
373
+ """
374
+ Re-score pairs combining geometric score with spatial proximity
375
+ after aligning cand centroids to the index frame.
376
+
377
+ final_score = alpha * geometric_score + (1 - alpha) * spatial_score
378
+ spatial_score = exp(- d² / (2 · spatial_sigma²)) # Gaussian, σ default 3 m
379
+ """
380
+ # Apply R, t to cand centroids only (fast; full geometry updated later)
381
+ aligned_cand_centroids = {
382
+ bid: self.R @ np.asarray(data['centroid'], dtype=np.float64) + self.t
383
+ for bid, data in object_dict['cands'].items()
384
+ }
385
+ index_centroids = {
386
+ bid: np.asarray(data['centroid'], dtype=np.float64)
387
+ for bid, data in object_dict['index'].items()
388
+ }
389
+
390
+ rescored = []
391
+ for cid, iid, geo_score in scored_pairs:
392
+ if cid in aligned_cand_centroids and iid in index_centroids:
393
+ dist = float(np.linalg.norm(aligned_cand_centroids[cid] - index_centroids[iid]))
394
+ # Gaussian decay with σ = spatial_sigma (default 3 m, ≈ median true-match
395
+ # residual). Sharply suppresses look-alikes that land 5–10 m away while
396
+ # giving high scores to genuine matches at d ≤ σ.
397
+ spatial_score = float(np.exp(-(dist * dist) / (2.0 * self.spatial_sigma ** 2)))
398
+ final_score = self.alpha * geo_score + (1.0 - self.alpha) * spatial_score
399
+ else:
400
+ final_score = geo_score # fallback if ID missing
401
+ rescored.append((cid, iid, final_score))
402
+
403
+ # Log score distribution summary
404
+ geo_scores = [s for _, _, s in scored_pairs]
405
+ final_scores = [s for _, _, s in rescored]
406
+ self.logger.info(
407
+ f"[RigidAligner] Score re-scaling: "
408
+ f"geometric mean={np.mean(geo_scores):.3f} → "
409
+ f"final mean={np.mean(final_scores):.3f} "
410
+ f"(alpha={self.alpha})"
411
+ )
412
+ return rescored
413
+
414
+ def _apply_transform_to_geometry(self, cands: dict) -> None:
415
+ """Apply (R, t) to all cand vertices, centroids, and polygon_mesh."""
416
+ for building in cands.values():
417
+ verts = building['vertices']
418
+ building['vertices'] = (self.R @ verts.T).T + self.t
419
+ building['centroid'] = self.R @ np.asarray(building['centroid'], dtype=np.float64) + self.t
420
+ new_mesh = []
421
+ for surface in building['polygon_mesh']:
422
+ new_surface = [(self.R @ np.array(c, dtype=np.float64) + self.t).tolist() for c in surface]
423
+ new_mesh.append(new_surface)
424
+ building['polygon_mesh'] = new_mesh
425
+
426
+ # ------------------------------------------------------------------ #
427
+ # CityJSON output
428
+ # ------------------------------------------------------------------ #
429
+
430
+ def _write_cityjson(self, cands: dict, suffix: str) -> None:
431
+ """
432
+ Write aligned candidates to a CityJSON 1.1 file in the index CRS.
433
+
434
+ Vertices are stored as floating-point world coordinates (no re-quantization).
435
+ Each building is written as a Solid LOD2 geometry preserving the original
436
+ surface structure.
437
+ """
438
+ results_dir = cfg.FilePaths.results_path
439
+ os.makedirs(results_dir, exist_ok=True)
440
+ out_path = os.path.join(results_dir, f"aligned_candidates_{suffix}.json")
441
+
442
+ city_objects = {}
443
+ all_vertices = []
444
+ vertex_index = {} # (x, y, z) rounded → global index
445
+
446
+ epsg_code = self.output_crs.split(":")[-1]
447
+
448
+ for bid, building in cands.items():
449
+ verts = building['vertices'] # (N, 3) already aligned
450
+
451
+ # Build local vertex index
452
+ local_idx = {}
453
+ for v in verts:
454
+ key = (round(float(v[0]), 6), round(float(v[1]), 6), round(float(v[2]), 6))
455
+ if key not in vertex_index:
456
+ vertex_index[key] = len(all_vertices)
457
+ all_vertices.append(list(key))
458
+ local_idx[key] = vertex_index[key]
459
+
460
+ # Encode polygon_mesh as surface boundary index lists
461
+ boundaries = []
462
+ for surface in building['polygon_mesh']:
463
+ ring = []
464
+ for coord in surface:
465
+ key = (round(float(coord[0]), 6), round(float(coord[1]), 6), round(float(coord[2]), 6))
466
+ # Find the nearest stored key (handles float drift)
467
+ if key not in vertex_index:
468
+ key = min(
469
+ local_idx.keys(),
470
+ key=lambda k: (k[0]-key[0])**2 + (k[1]-key[1])**2 + (k[2]-key[2])**2
471
+ )
472
+ ring.append(vertex_index[key])
473
+ boundaries.append([ring])
474
+
475
+ city_objects[f"bag_{bid}"] = {
476
+ "type": "Building",
477
+ "geometry": [{
478
+ "type": "Solid",
479
+ "lod": "2",
480
+ "boundaries": [boundaries]
481
+ }],
482
+ "attributes": building.get("attributes", {})
483
+ }
484
+
485
+ cityjson = {
486
+ "type": "CityJSON",
487
+ "version": "1.1",
488
+ "metadata": {
489
+ "referenceSystem": f"https://www.opengis.net/def/crs/EPSG/0/{epsg_code}"
490
+ },
491
+ "CityObjects": city_objects,
492
+ "vertices": all_vertices,
493
+ "alignment_info": {
494
+ "mean_residual_m": round(self.mean_residual, 3),
495
+ "n_anchor_pairs": self.n_anchors,
496
+ "alpha": self.alpha
497
+ }
498
+ }
499
+
500
+ with open(out_path, 'w', encoding='utf-8') as f:
501
+ json.dump(cityjson, f, indent=2)
502
+
503
+ size_mb = os.path.getsize(out_path) / 1e6
504
+ self.logger.info(
505
+ f"[RigidAligner] Aligned CityJSON written: {out_path} "
506
+ f"({len(city_objects)} buildings, {size_mb:.1f} MB)"
507
+ )
code/3dSAGER/config.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ class FilePaths:
4
+ results_path = "results/"
5
+ saved_models_path = "saved_model_files/"
6
+ object_dict_path = "data/object_dicts/"
7
+ dataset_dict_path = "data/dataset_dicts/"
8
+ property_dict_path = "data/property_dicts/"
9
+ dataset_partition_path = "data/dataset_partitions/"
10
+
11
+
12
+ class Constants:
13
+ dataset_name = "Hague" # "Hague", "delivery3", "bo_em", "gpkg"
14
+ synthetic_folder_name = "example" # Relevant only if dataset_name is "synthetic"
15
+ evaluation_mode = "matching" # "blocking", "matching"
16
+ dataset_size_version = 'medium' # 'small', 'medium', 'large'
17
+ matching_cands_generation = 'negative_sampling' # 'negative_sampling', 'blocking-based'
18
+ neg_samples_num = 2 # 2, 5
19
+ seeds_num = 1
20
+ train_ratio = 0.6
21
+ val_ratio = 0.2
22
+ test_ratio = 1 - train_ratio - val_ratio
23
+ max_ratio_val = 1000 # Avoid infinity values
24
+ load_object_dict = False # Must be False when disaster simulation is active
25
+ save_object_dict = True # Cache object dict to avoid reloading from disk
26
+ load_train_items = False # Load existing preparatory items
27
+ save_property_dict = True # Cache property dict to avoid recomputing
28
+ load_property_dict = False # Load the properties dictionary
29
+ save_dataset_dict = True # Cache dataset dict to avoid recomputing
30
+ load_dataset_dict = False # load existing dataset dictionary
31
+ file_name_suffix = 'allmodels_v1' # Stable suffix so model files are reusable across runs
32
+ max_grid_cells = 20 # None = all cells; 50 = medium run on 8GB RAM
33
+
34
+
35
+ class TrainingPhase:
36
+ training_ratio = 0.5 # Number of positive samples
37
+ neg_pairs_ratio = 4 # Number of negative samples per positive sample
38
+ run_preparatory_phase = True # If False, the preparatory phase will not be run
39
+
40
+
41
+ class Features:
42
+ knn_buildings = 0 # Number of nearest buildings to consider
43
+ knn_roads = 0 # Number of nearest roads to consider
44
+ operator = 'division' # 'division', 'concatenation'
45
+ object_properties = ["bounding_box_width", "bounding_box_length", "area", "perimeter", "perimeter_ind",
46
+ "volume", "convex_hull_area", "convex_hull_volume", "ave_centroid_distance", "height_diff",
47
+ "num_floors", "axes_symmetry", "compactness_2d", "compactness_3d", "density",
48
+ "elongation", "shape_ind", "hemisphericality", "fractality", "cubeness", "circumference",
49
+ "aligned_bounding_box_width", "aligned_bounding_box_length", "aligned_bounding_box_height",
50
+ "num_vertices"]
51
+
52
+ # object_properties = ["circumference", "density", "convex_hull_area"]
53
+ normalization = 'log_transform' # 'log_transform', None
54
+ neighborhood = []
55
+ roads = []
56
+
57
+
58
+ class Blocking:
59
+ blocking_method = 'bkafi' # 'bkafi', 'bkafi_without_SDR', 'ViT-B_32', 'ViT-L_14', 'centroid'
60
+ # 'coordinates', 'coordinates_transformed'
61
+ cand_pairs_per_item_list = [i for i in range(1, 21)] # total number of neighbors per each candidate object
62
+ nn_param = cand_pairs_per_item_list[-1] + 1 # number of nearest neighbors to retrieve as candidates
63
+ nbits = 10 # number of bits to use for LSH
64
+ # bkafi_dim_list = [dim for dim in range(1, len(Features.object_properties))] # Number of important features to
65
+ # use for blocking (for the bkafi method)
66
+ bkafi_dim_list = [dim for dim in range(1, len(Features.object_properties))] # Number of important features to use
67
+ dist_threshold = None # Define it as a hyperparameter or in a flexible manner
68
+ sdr_factor = False # If True, the SDR factor will be used in the blocking method
69
+ bkafi_criterion = 'feature_importance' # 'std', 'feature_importance'
70
+ # Neighborhood-aware negative sampling
71
+ neighborhood_radius = 500.0 # meters (EPSG:7415) — radius for spatial negative sampling
72
+ neighborhood_neg_ratio = 0.7 # fraction of negatives drawn from within-radius neighbors vs. random
73
+
74
+
75
+ class DataPartition:
76
+ grid_cell_size = 500.0 # meters (EPSG:7415) — side length of each spatial grid cell
77
+ train_ratio = 0.6 # fraction of grid cells assigned to training
78
+ contiguous_test = True # If True, test cells form a spatially contiguous region (BFS from
79
+ # a corner) so the demo app covers a coherent train-only area.
80
+
81
+
82
+ class DisasterSimulation:
83
+ enabled = True
84
+ # CRS simulation — random rotation + large translation applied globally to all cands
85
+ crs_simulation = True # simulate unknown CRS (no absolute reference)
86
+ # Damage simulation — per-building random height reduction
87
+ damage_probability = 0.8 # fraction of cand buildings to damage
88
+ min_damage_factor = 0.3 # minimum remaining height fraction (0.3 = 70% collapsed)
89
+ max_damage_factor = 0.95 # maximum remaining height fraction (near-undamaged)
90
+
91
+
92
+ class Alignment:
93
+ enabled = True
94
+ min_anchor_pairs = 3 # minimum high-confidence matches required to attempt alignment
95
+ confidence_threshold = 0.8 # geometric classifier score threshold for anchor selection
96
+ max_residual_threshold = 50.0 # meters — reject alignment if mean anchor error exceeds this
97
+ alpha = 0.5 # weight: 1.0 = geometric score only, 0.0 = spatial score only
98
+ output_crs = "EPSG:7415" # index dataset CRS — output aligned CityJSON in this CRS
99
+ use_ransac = True # use RANSAC to find robust transform instead of plain SVD
100
+ ransac_iterations = 1000 # number of RANSAC trials
101
+ ransac_inlier_threshold = 10.0 # meters — anchor is inlier if residual < this after applying R, t
102
+ spatial_sigma = 3.0 # meters — Gaussian decay length for post-alignment spatial score.
103
+ # spatial(d) = exp(-d²/(2·σ²)). σ ≈ median true-match residual;
104
+ # σ=3 m gives spatial(0)=1, spatial(3)=0.61, spatial(10)≈0.004.
105
+ post_align_knn_cutoff = 7.0 # meters — for --post-align-blocking mode in demo/inference.py.
106
+ # After alignment succeeds, replace BKAFI pool with per-cand 1-NN
107
+ # against full index; accept iff post-alignment distance ≤ cutoff.
108
+
109
+
110
+ class Models:
111
+ load_trained_models = False
112
+ cv = 3
113
+ model_to_use = 'XGBClassifier' # Used only for predict.py and feature_importances.py
114
+ model_list = ['XGBClassifier', # 'GradientBoostingClassifier', 'BaggingClassifier',
115
+ 'RandomForestClassifier', 'AdaBoostClassifier', 'MLPClassifier']
116
+ blocking_model = 'RandomForestClassifier' # Used only for blocking and for advanced evaluation
117
+ params_dict = {
118
+ 'RandomForestClassifier': {"n_estimators": [50],
119
+ "max_depth": [5],
120
+ "min_samples_split": [2],
121
+ "max_features": ["sqrt"]},
122
+
123
+ 'SVC': {'C': [0.1, 0.5],
124
+ 'kernel': ['rbf'],
125
+ 'gamma': ['scale'],
126
+ 'degree': [2]
127
+ },
128
+
129
+ 'LogisticRegression': {'solver': ['lbfgs', 'saga'],
130
+ 'multi_class': ['auto'],
131
+ 'C': [0.01, 0.1, 1]
132
+ },
133
+
134
+ 'MLPClassifier': {'hidden_layer_sizes': [(64, 32)],
135
+ 'activation': ['relu'],
136
+ 'solver': ['adam'],
137
+ 'batch_size': [16],
138
+ 'max_iter': [500],
139
+ 'early_stopping': [True],
140
+ 'n_iter_no_change': [20],
141
+ },
142
+
143
+ 'AdaBoostClassifier': {'n_estimators': [100],
144
+ 'learning_rate': [0.1],
145
+ 'algorithm': ['SAMME']
146
+ },
147
+
148
+ 'GradientBoostingClassifier': {'loss': ['log_loss'],
149
+ 'learning_rate': [0.1],
150
+ 'n_estimators': [100],
151
+ 'max_depth': [3],
152
+ 'min_samples_split': [3],
153
+ 'max_features': ['sqrt']
154
+ },
155
+
156
+ 'BaggingClassifier': {'n_estimators': [50],
157
+ 'max_samples': [0.8],
158
+ 'max_features': [0.8],
159
+ 'bootstrap': [True]
160
+ },
161
+
162
+ 'XGBClassifier': {'max_depth': [4],
163
+ 'objective': ['binary:logistic'],
164
+ 'learning_rate': [0.1],
165
+ 'n_estimators': [100],
166
+ 'gamma': [0],
167
+ 'tree_method': ['hist'],
168
+ 'n_jobs': [4],
169
+ }
170
+ }
171
+
172
+
173
+
code/3dSAGER/dataset_configs.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bo_em": {
3
+ "cands_path": "data/240823/em/",
4
+ "index_path": "data/240823/bo/",
5
+ "roads_path": "data/roads/roads1.geojson",
6
+ "general_file_name": "em_bo1",
7
+ "object_dict_path": "data/240823/"
8
+ },
9
+ "gpkg": {
10
+ "cands_path": "data/200224/history2021/",
11
+ "index_path": "data/200224/solid2021/",
12
+ "roads_path": "data/roads/roads1.geojson",
13
+ "general_file_name": "gpkg1",
14
+ "object_dict_path": "data/200224/"
15
+ },
16
+ "delivery3": {
17
+ "index_path": "data/210424/all_pairs/set_1/new/",
18
+ "cands_path": "data/210424/all_pairs/set_2/new/",
19
+ "roads_path": "data/roads/roads1.geojson",
20
+ "general_file_name": "delivery3_all_pairs",
21
+ "object_dict_path": "data/210424/all_pairs/"
22
+ },
23
+ "Hague": {
24
+ "cands_path": "../The Hague/Source B/",
25
+ "index_path": "../The Hague/Source A/",
26
+ "roads_path": "",
27
+ "general_file_name": "Hague",
28
+ "object_dict_path": "data/object_dicts/Hague/"
29
+ },
30
+ "synthetic_example": {
31
+ "cands_path": "data/synthetic/example/LOD3-0.2.json",
32
+ "index_path": "data/synthetic/example/LOD3.json",
33
+ "roads_path": "",
34
+ "general_file_name": "synthetic_example"
35
+ }
36
+ }
code/3dSAGER/disaster_simulation.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ disaster_simulation.py
3
+
4
+ Simulates a post-disaster scenario on the candidate building set.
5
+
6
+ Two independent simulations are applied in order (CRS first, then damage):
7
+
8
+ 1. CRS simulation (global):
9
+ All cand buildings are rotated by a random angle around the Z-axis and shifted
10
+ by a large random translation, simulating a dataset with no absolute coordinate
11
+ reference. The internal geometry of each building is preserved exactly; only
12
+ the global frame changes. This forces the model to rely on rotation-invariant
13
+ features (aligned BB, volume, area, compactness) rather than axis-aligned ones.
14
+
15
+ 2. Damage simulation (per-building):
16
+ A random subset of cand buildings have their height reduced, simulating partial
17
+ collapse. Each damaged building keeps its ground footprint but loses height
18
+ according to a random damage factor.
19
+
20
+ Only 'cands' are ever modified. The 'index' (reference dataset) is never touched.
21
+
22
+ Usage:
23
+ from disaster_simulation import DisasterSimulator
24
+ import config
25
+
26
+ simulator = DisasterSimulator(config.DisasterSimulation, seed=1)
27
+ object_dict = simulator.apply(object_dict)
28
+ # simulator.R_crs, simulator.t_crs — ground-truth transform for evaluation
29
+ # simulator.damage_log — per-building damage factors for inspection
30
+ """
31
+
32
+ import numpy as np
33
+ import config as cfg
34
+
35
+
36
+ class DisasterSimulator:
37
+ """
38
+ Applies CRS simulation and damage simulation to the candidate set.
39
+
40
+ Parameters
41
+ ----------
42
+ sim_config : config.DisasterSimulation (class reference)
43
+ seed : int
44
+ Controls randomness for both simulations. Different seeds per pipeline
45
+ run ensure the model trains on varied scenarios.
46
+ """
47
+
48
+ _Z_EPSILON = 1e-4 # threshold to distinguish above-ground vertices from ground
49
+
50
+ def __init__(self, sim_config=None, seed=42):
51
+ if sim_config is None:
52
+ sim_config = cfg.DisasterSimulation
53
+ self.enabled = sim_config.enabled
54
+ self.crs_simulation = sim_config.crs_simulation
55
+ self.damage_probability = sim_config.damage_probability
56
+ self.min_damage_factor = sim_config.min_damage_factor
57
+ self.max_damage_factor = sim_config.max_damage_factor
58
+ self._rng = np.random.default_rng(seed)
59
+
60
+ # Set after apply() — expose for external evaluation
61
+ self.R_crs = None # (3,3) rotation matrix applied to all cands
62
+ self.t_crs = None # (3,) translation vector applied to all cands
63
+ self.damage_log = {} # {building_id: damage_factor} (1.0 = undamaged)
64
+
65
+ # ------------------------------------------------------------------ #
66
+ # Public API
67
+ # ------------------------------------------------------------------ #
68
+
69
+ def apply(self, object_dict: dict) -> dict:
70
+ """
71
+ Apply CRS simulation then damage simulation to cands in-place.
72
+
73
+ Parameters
74
+ ----------
75
+ object_dict : dict
76
+ Full object dict with keys 'cands', 'index', 'mapping_dict', etc.
77
+
78
+ Returns
79
+ -------
80
+ dict
81
+ Same object_dict with modified cands.
82
+ """
83
+ if not self.enabled:
84
+ return object_dict
85
+
86
+ if self.crs_simulation:
87
+ object_dict = self._apply_crs_simulation(object_dict)
88
+
89
+ object_dict = self._apply_damage_simulation(object_dict)
90
+
91
+ self._print_summary(object_dict)
92
+ return object_dict
93
+
94
+ # ------------------------------------------------------------------ #
95
+ # CRS simulation
96
+ # ------------------------------------------------------------------ #
97
+
98
+ def _apply_crs_simulation(self, object_dict: dict) -> dict:
99
+ """
100
+ Apply a single random rotation (around Z) + large translation to ALL cands.
101
+
102
+ The same (R_crs, t_crs) is applied to every building so internal
103
+ relative geometry is preserved — only the global frame changes.
104
+ """
105
+ # Random rotation angle in [0, 2π)
106
+ theta = self._rng.uniform(0.0, 2.0 * np.pi)
107
+ cos_t, sin_t = np.cos(theta), np.sin(theta)
108
+ self.R_crs = np.array([
109
+ [ cos_t, -sin_t, 0.0],
110
+ [ sin_t, cos_t, 0.0],
111
+ [ 0.0, 0.0, 1.0]
112
+ ])
113
+
114
+ # Large random translation — no absolute reference
115
+ tx = self._rng.uniform(-100_000.0, 100_000.0)
116
+ ty = self._rng.uniform(-100_000.0, 100_000.0)
117
+ self.t_crs = np.array([tx, ty, 0.0])
118
+
119
+ for bid, building in object_dict['cands'].items():
120
+ self._transform_building(building, self.R_crs, self.t_crs)
121
+
122
+ print(f"[DisasterSimulator] CRS simulation applied: "
123
+ f"rotation={np.degrees(theta):.1f}°, "
124
+ f"translation=({tx:.0f}, {ty:.0f}) m")
125
+ return object_dict
126
+
127
+ @staticmethod
128
+ def _transform_building(building: dict, R: np.ndarray, t: np.ndarray) -> None:
129
+ """Apply rigid transform (R, t) to all geometry of one building in-place."""
130
+ # vertices: (N, 3)
131
+ verts = building['vertices']
132
+ building['vertices'] = (R @ verts.T).T + t
133
+
134
+ # centroid: (3,)
135
+ building['centroid'] = R @ np.asarray(building['centroid'], dtype=np.float64) + t
136
+
137
+ # polygon_mesh: list of surfaces, each surface = list of [x, y, z]
138
+ new_mesh = []
139
+ for surface in building['polygon_mesh']:
140
+ new_surface = []
141
+ for coord in surface:
142
+ v = np.array(coord, dtype=np.float64)
143
+ new_surface.append((R @ v + t).tolist())
144
+ new_mesh.append(new_surface)
145
+ building['polygon_mesh'] = new_mesh
146
+
147
+ # ------------------------------------------------------------------ #
148
+ # Damage simulation
149
+ # ------------------------------------------------------------------ #
150
+
151
+ def _apply_damage_simulation(self, object_dict: dict) -> dict:
152
+ """
153
+ Randomly reduce height of a fraction of cand buildings.
154
+
155
+ Each damaged building keeps its ground footprint but all vertices
156
+ above z_min are scaled: z_new = z_min + (z - z_min) * damage_factor
157
+ """
158
+ cands = object_dict['cands']
159
+ cand_ids = list(cands.keys())
160
+ n_to_damage = int(round(self.damage_probability * len(cand_ids)))
161
+
162
+ # Select which buildings to damage
163
+ damaged_indices = self._rng.choice(len(cand_ids), size=n_to_damage, replace=False)
164
+ damaged_ids = [cand_ids[i] for i in damaged_indices]
165
+
166
+ # One damage factor per building
167
+ damage_factors = self._rng.uniform(
168
+ self.min_damage_factor, self.max_damage_factor, size=n_to_damage
169
+ )
170
+
171
+ for bid, factor in zip(damaged_ids, damage_factors):
172
+ self._damage_building(cands[bid], factor)
173
+ self.damage_log[bid] = round(float(factor), 4)
174
+
175
+ # Undamaged buildings recorded as 1.0
176
+ for bid in cand_ids:
177
+ if bid not in self.damage_log:
178
+ self.damage_log[bid] = 1.0
179
+
180
+ print(f"[DisasterSimulator] Damage simulation: "
181
+ f"{n_to_damage}/{len(cand_ids)} buildings damaged "
182
+ f"(factor range [{self.min_damage_factor}, {self.max_damage_factor}])")
183
+ return object_dict
184
+
185
+ def _damage_building(self, building: dict, damage_factor: float) -> None:
186
+ """Reduce height of a single building in-place."""
187
+ verts = building['vertices'] # (N, 3)
188
+ z_min = float(verts[:, 2].min())
189
+
190
+ # Update vertices array
191
+ mask = verts[:, 2] > (z_min + self._Z_EPSILON)
192
+ verts[mask, 2] = z_min + (verts[mask, 2] - z_min) * damage_factor
193
+ building['vertices'] = verts
194
+
195
+ # Update polygon_mesh
196
+ new_mesh = []
197
+ for surface in building['polygon_mesh']:
198
+ new_surface = []
199
+ for coord in surface:
200
+ x, y, z = coord[0], coord[1], coord[2]
201
+ if z > z_min + self._Z_EPSILON:
202
+ z = z_min + (z - z_min) * damage_factor
203
+ new_surface.append([x, y, z])
204
+ new_mesh.append(new_surface)
205
+ building['polygon_mesh'] = new_mesh
206
+
207
+ # Update centroid z
208
+ new_z_max = float(verts[:, 2].max())
209
+ c = np.asarray(building['centroid'], dtype=np.float64)
210
+ c[2] = (z_min + new_z_max) / 2.0
211
+ building['centroid'] = c
212
+
213
+ # ------------------------------------------------------------------ #
214
+ # Reporting
215
+ # ------------------------------------------------------------------ #
216
+
217
+ @staticmethod
218
+ def _print_summary(object_dict: dict) -> None:
219
+ print(f"[DisasterSimulator] Done. "
220
+ f"cands: {len(object_dict['cands'])}, "
221
+ f"index: {len(object_dict['index'])} (unchanged)")
code/3dSAGER/main.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import config
2
+ import argparse
3
+ from utils import *
4
+ from pipelines import PipelineManager
5
+ import warnings
6
+
7
+ warnings.filterwarnings("ignore")
8
+
9
+
10
+
11
+ if __name__ == "__main__":
12
+ parser = argparse.ArgumentParser()
13
+ parser.add_argument('--dataset_name', type=str, default=config.Constants.dataset_name)
14
+ parser.add_argument('--evaluation_mode', type=str, default=config.Constants.evaluation_mode)
15
+ parser.add_argument('--run_preparatory_phase', type=bool, default=config.TrainingPhase.run_preparatory_phase)
16
+ parser.add_argument('--blocking_method', type=str, default=config.Blocking.blocking_method)
17
+ parser.add_argument('--seeds_num', type=int, default=config.Constants.seeds_num)
18
+ parser.add_argument('--dataset_size_version', type=str, default=config.Constants.dataset_size_version)
19
+ parser.add_argument('--vector_normalization', type=str2bool, default=True)
20
+ parser.add_argument('--sdr_factor', type=str2bool, default=False)
21
+ parser.add_argument('--neg_samples_num', type=int, default=config.Constants.neg_samples_num)
22
+ parser.add_argument('--bkafi_criterion', type=str, default=config.Blocking.bkafi_criterion)
23
+ parser.add_argument('--run_blocker_train', type=str2bool, default=False)
24
+ parser.add_argument('--matching_cands_generation', type=str,
25
+ default=config.Constants.matching_cands_generation)
26
+ parser.add_argument('--contamination_mode', type=str2bool, default=False)
27
+
28
+ args = parser.parse_args()
29
+ logger = define_logger()
30
+ print_config(logger, args)
31
+ result_dict = {}
32
+ for seed in range(1, args.seeds_num+1):
33
+ logger.info(f"Seed: {seed}")
34
+ logger.info(3*'--------------------------')
35
+ pipeline_manager_obj = PipelineManager(seed, logger, args)
36
+ result_dict[seed] = pipeline_manager_obj.result_dict
37
+ if not args.run_blocker_train:
38
+ generate_final_result_csv(result_dict, args)
39
+ logger.info("Done!")
40
+
41
+
code/3dSAGER/pipelines.py ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import os
4
+ import config
5
+ from utils import *
6
+ from blocking import Blocker
7
+ from collections import defaultdict
8
+ from process_pairs import PairProcessor
9
+ from object_properties import ObjectPropertiesProcessor
10
+ import numpy as np
11
+ from sklearn.model_selection import train_test_split
12
+ from classifier import FlexibleClassifier
13
+ from abc import ABC, abstractmethod
14
+ from multiprocessing import Pool, cpu_count
15
+ from disaster_simulation import DisasterSimulator
16
+ from alignment import RigidAligner
17
+
18
+
19
+ class PipelineManager:
20
+ def __init__(self, seed, logger, args, min_surfaces_num=10):
21
+ self.dataset_name = args.dataset_name
22
+ self.seed = seed
23
+ self.logger = logger
24
+ self.with_prep_training = args.run_preparatory_phase
25
+ self.min_surfaces_num = min_surfaces_num
26
+ self.evaluation_mode = args.evaluation_mode
27
+ self.blocking_method = args.blocking_method
28
+ self.dataset_size_version = args.dataset_size_version
29
+ self.neg_samples_num = args.neg_samples_num
30
+ self.vector_normalization = args.vector_normalization
31
+ self.sdr_factor = args.sdr_factor
32
+ self.bkafi_criterion = args.bkafi_criterion
33
+ self.matching_cands_generation = args.matching_cands_generation
34
+ self.run_blocker_train = args.run_blocker_train
35
+ self._simulator = None # set by _read_objects when disaster simulation runs
36
+ self.dataset_dict = self._create_dataset_dict()
37
+ self.flexible_classifier_obj = self._train_and_evaluate()
38
+ self.result_dict = self._get_result_dict()
39
+
40
+ def _read_objects(self):
41
+ dataset_config = json.load(open('dataset_configs.json'))[self.dataset_name]
42
+ train_object_dict, test_object_dict = self._load_object_dict_wrapper()
43
+ partition_path = (f"{config.FilePaths.dataset_partition_path}"
44
+ f"{self.dataset_name}_seed{self.seed}.pkl")
45
+ if not os.path.exists(partition_path):
46
+ self.logger.info(f"Partition file missing — generating for seed {self.seed}...")
47
+ import argparse
48
+ from data_partition import DataPartitionGenerator
49
+ partition_args = argparse.Namespace(
50
+ dataset_name=self.dataset_name,
51
+ train_neg_samples_list=[2, 5],
52
+ train_size_ratio_list={"small": 0.1, "medium": 0.4, "large": 0.6},
53
+ test_size_ratio_list={"small": 0.1, "medium": 0.5, "large": 1.0},
54
+ test_negative_samples_list=[2, 5],
55
+ )
56
+ gen = DataPartitionGenerator(partition_args)
57
+ gen.create_dataset_partition_dict(self.seed)
58
+ data_partition_dict = load_dataset_partition_dict(self.dataset_name, self.logger, self.seed)
59
+ if test_object_dict is not None and train_object_dict is not None:
60
+ return data_partition_dict, train_object_dict, test_object_dict
61
+ self.logger.info("Generating test object dict and train object dict")
62
+ # Raw-object cache: produced by preprocess_hague.py (run once).
63
+ # If missing, fall back to reading CityJSON files directly.
64
+ # Each seed deepcopies before simulation so the cached version is never mutated.
65
+ raw_cache_path = (f"{config.FilePaths.object_dict_path}"
66
+ f"{self.dataset_name}_raw.joblib")
67
+ if os.path.exists(raw_cache_path):
68
+ self.logger.info(f"Loading preprocessed cache: {raw_cache_path}")
69
+ raw_object_dict = joblib.load(raw_cache_path)
70
+ self.logger.info(
71
+ f" → {len(raw_object_dict['cands'])} cands, "
72
+ f"{len(raw_object_dict['index'])} index buildings"
73
+ )
74
+ else:
75
+ self.logger.info("No preprocessed cache found — running full read (slow).")
76
+ raw_object_dict = getattr(self, f'_read_objects_{self.dataset_name}')(dataset_config)
77
+ os.makedirs(os.path.dirname(raw_cache_path), exist_ok=True)
78
+ joblib.dump(raw_object_dict, raw_cache_path, compress=3)
79
+ self.logger.info(f"Raw object_dict cached to: {raw_cache_path}")
80
+ # Optional: restrict to the first N shared grid cells for quick testing
81
+ max_cells = config.Constants.max_grid_cells
82
+ if max_cells is not None and 'grid_meta' in raw_object_dict:
83
+ raw_object_dict = self._filter_to_grid_cells(raw_object_dict, max_cells)
84
+ # Work on a fresh copy so the cached version is never modified by simulation
85
+ object_dict = copy.deepcopy(raw_object_dict)
86
+ # Apply disaster simulation to cands before property extraction.
87
+ # load_object_dict must be False when disaster mode is active (cached dicts
88
+ # are pre-simulation and would produce incorrect features).
89
+ self._simulator = DisasterSimulator(config.DisasterSimulation, seed=self.seed)
90
+ object_dict = self._simulator.apply(object_dict)
91
+ train_object_dict, test_object_dict = self._partition_object_dict(object_dict, data_partition_dict)
92
+ if config.Constants.save_object_dict:
93
+ self._save_object_dicts(train_object_dict, test_object_dict, dataset_config)
94
+ return data_partition_dict, train_object_dict, test_object_dict
95
+
96
+ @staticmethod
97
+ def _filter_to_grid_cells(raw_object_dict, max_cells):
98
+ """
99
+ Restrict both cands and index to buildings in the `max_cells` most-populated
100
+ grid cells that are shared between both sources.
101
+ Picking by population (not coordinate order) maximises pair coverage from the
102
+ pre-built partition dict and ensures a spatially representative quick test.
103
+ """
104
+ from collections import Counter
105
+ cands_cells = set(b['grid_cell'] for b in raw_object_dict['cands'].values())
106
+ index_cells = set(b['grid_cell'] for b in raw_object_dict['index'].values())
107
+ shared = cands_cells & index_cells
108
+ # Sort shared cells by number of cands in descending order
109
+ cell_pop = Counter(b['grid_cell'] for b in raw_object_dict['cands'].values())
110
+ shared_cells = set(sorted(shared, key=lambda c: -cell_pop[c])[:max_cells])
111
+
112
+ filtered = dict(raw_object_dict) # shallow copy of top-level keys
113
+ filtered['cands'] = {k: v for k, v in raw_object_dict['cands'].items()
114
+ if v['grid_cell'] in shared_cells}
115
+ filtered['index'] = {k: v for k, v in raw_object_dict['index'].items()
116
+ if v['grid_cell'] in shared_cells}
117
+
118
+ # Rebuild mapping dicts for filtered subset
119
+ filtered['mapping_dict'] = {}
120
+ filtered['inv_mapping_dict'] = {}
121
+ for src in ('cands', 'index'):
122
+ keys = sorted(filtered[src].keys())
123
+ filtered['mapping_dict'][src] = {i: k for i, k in enumerate(keys)}
124
+ filtered['inv_mapping_dict'][src] = {k: i for i, k in enumerate(keys)}
125
+
126
+ import logging
127
+ logging.getLogger(__name__).info(
128
+ f"[grid filter] {max_cells} shared cells → "
129
+ f"{len(filtered['cands'])} cands, {len(filtered['index'])} index buildings"
130
+ )
131
+ return filtered
132
+
133
+ def _load_object_dict_wrapper(self):
134
+ test_object_dict, train_object_dict = None, None
135
+ train_full_path, test_full_path = self._get_object_dict_paths()
136
+ if config.Constants.load_object_dict:
137
+ train_object_dict = load_object_dict(self.logger, train_full_path, 'train_object_dict')
138
+ test_object_dict = load_object_dict(self.logger, test_full_path, 'test_object_dict')
139
+ return train_object_dict, test_object_dict
140
+
141
+ def _save_object_dicts(self, train_object_dict, test_object_dict, dataset_config):
142
+ self._print_object_dict_stats(train_object_dict, test_object_dict)
143
+ self.logger.info(f"Saving test object dict")
144
+ train_full_path, test_full_path = self._get_object_dict_paths()
145
+ self.logger.info(f"Saving train object dict to {train_full_path}")
146
+ joblib.dump(train_object_dict, train_full_path)
147
+ self.logger.info(f"Saving test object dict to {test_full_path}")
148
+ joblib.dump(test_object_dict, test_full_path)
149
+ return
150
+
151
+ @staticmethod
152
+ def _print_object_dict_stats(train_object_dict, test_object_dict):
153
+ print(f"Number of cands in train: {len(train_object_dict['cands'])}")
154
+ print(f"Number of index in train: {len(train_object_dict['index'])}")
155
+ print(f"Number of cands in test: {len(test_object_dict['cands'])}")
156
+ print(f"Number of index in test: {len(test_object_dict['index'])}")
157
+
158
+ def _get_object_dict_paths(self):
159
+ object_dict_path = f"{config.FilePaths.object_dict_path}{self.dataset_name}/"
160
+ if not os.path.exists(object_dict_path):
161
+ os.makedirs(object_dict_path)
162
+ if self.evaluation_mode == 'blocking':
163
+ train_full_path = f"{object_dict_path}train_blocking_{self.dataset_size_version}"
164
+ test_full_path = f"{object_dict_path}test_blocking_{self.dataset_size_version}"
165
+ else:
166
+ train_full_path = (f"{object_dict_path}train_matching_{self.dataset_size_version}_"
167
+ f"neg_samples_num={self.neg_samples_num}")
168
+ test_full_path = f"{object_dict_path}test_matching_{self.matching_cands_generation}" \
169
+ f"_{self.dataset_size_version}_neg_samples_num={self.neg_samples_num}"
170
+ return f"{train_full_path}_seed_{self.seed}.joblib", f"{test_full_path}_seed_{self.seed}.joblib"
171
+
172
+ def _partition_object_dict(self, object_dict, data_partition_dict):
173
+ if self.evaluation_mode == "blocking":
174
+ return self._clean_object_dict_blocking(object_dict, data_partition_dict)
175
+ else:
176
+ return self._clean_object_dict_matching(object_dict, data_partition_dict)
177
+
178
+ def _clean_object_dict_blocking(self, object_dict, data_partition_dict):
179
+ dataset_version = self.dataset_size_version
180
+ train_object_dict = {'cands': {}, 'index': {}}
181
+ test_object_dict = {'cands': {}, 'index': {}}
182
+ avail_cands = set(object_dict['cands'].keys())
183
+ avail_index = set(object_dict['index'].keys())
184
+ train_pairs = data_partition_dict['train']['negative_sampling'][dataset_version][2]
185
+ train_pairs = [p for p in train_pairs if p[0] in avail_cands and p[1] in avail_index]
186
+ test_data_partition = data_partition_dict['test']['blocking'][dataset_version]
187
+ test_cands_ids = [i for i in test_data_partition['cands'] if i in avail_cands]
188
+ test_index_ids = [i for i in test_data_partition['index'] if i in avail_index]
189
+ train_object_dict['cands'] = {pair[0]: object_dict['cands'][pair[0]] for pair in train_pairs}
190
+ train_object_dict['index'] = {pair[1]: object_dict['index'][pair[1]] for pair in train_pairs}
191
+ test_object_dict['cands'] = {object_id: object_dict['cands'][object_id] for object_id in test_cands_ids}
192
+ test_object_dict['index'] = {object_id: object_dict['index'][object_id] for object_id in test_index_ids}
193
+ return train_object_dict, test_object_dict
194
+
195
+ def _clean_object_dict_matching(self, object_dict, data_partition_dict):
196
+ train_object_dict = {'cands': {}, 'index': {}}
197
+ test_object_dict = {'cands': {}, 'index': {}}
198
+ dataset_version = self.dataset_size_version
199
+ neg_num = self.neg_samples_num
200
+ candidates_generation = self.matching_cands_generation
201
+ train_pairs = data_partition_dict['train'][self.matching_cands_generation][dataset_version][neg_num]
202
+ test_pairs = data_partition_dict['test']['matching'][candidates_generation][dataset_version][neg_num]
203
+ # Filter pairs to IDs that exist in the loaded object_dict (important for
204
+ # quick-test runs where max_files_per_source limits coverage)
205
+ avail_cands = set(object_dict['cands'].keys())
206
+ avail_index = set(object_dict['index'].keys())
207
+ train_pairs = [p for p in train_pairs if p[0] in avail_cands and p[1] in avail_index]
208
+ test_pairs = [p for p in test_pairs if p[0] in avail_cands and p[1] in avail_index]
209
+ self.logger.info(f"Filtered to {len(train_pairs)} train pairs, {len(test_pairs)} test pairs "
210
+ f"(available cands={len(avail_cands)}, index={len(avail_index)})")
211
+ train_object_dict['cands'] = {pair[0]: object_dict['cands'][pair[0]] for pair in train_pairs}
212
+ train_object_dict['index'] = {pair[1]: object_dict['index'][pair[1]] for pair in train_pairs}
213
+ test_object_dict['cands'] = {pair[0]: object_dict['cands'][pair[0]] for pair in test_pairs}
214
+ test_object_dict['index'] = {pair[1]: object_dict['index'][pair[1]] for pair in test_pairs}
215
+ return train_object_dict, test_object_dict
216
+
217
+ @staticmethod
218
+ def _remove_train_objects_from_object_dict(object_dict, train_ids):
219
+ for objects_type in object_dict.keys():
220
+ object_dict[objects_type] = {
221
+ object_id: object_data
222
+ for object_id, object_data in object_dict[objects_type].items()
223
+ if object_id not in train_ids
224
+ }
225
+ return object_dict
226
+
227
+ @staticmethod
228
+ def _compute_object_centroid(vertices):
229
+ unique_vertices = np.array(vertices)
230
+ return unique_vertices.mean(axis=0)
231
+
232
+ @staticmethod
233
+ def _get_vertices(polygon_mesh):
234
+ return np.unique(np.array([coord for surface in polygon_mesh for coord in surface]), axis=0)
235
+
236
+ @staticmethod
237
+ def _get_polygon_mesh(data, obj_key, vertices, min_surfaces_num):
238
+ boundaries = data['CityObjects'][obj_key]['geometry'][0]['boundaries'][0]
239
+ if len(boundaries) < min_surfaces_num:
240
+ return None
241
+ polygon_mesh = []
242
+ for surface in boundaries:
243
+ polygon_mesh.append([vertices[i] for sub_surface_list in surface for i in sub_surface_list])
244
+ vertices = PipelineManager._get_vertices(polygon_mesh)
245
+ centroid = PipelineManager._compute_object_centroid(vertices)
246
+ return {'polygon_mesh': polygon_mesh, 'vertices': vertices, 'centroid': centroid}
247
+
248
+ def _insert_polygon_mesh(self, object_dict, obj_type, obj_data, obj_ind, min_surfaces_num=10):
249
+ vertices = obj_data['vertices']
250
+ obj_key = list(obj_data['CityObjects'].keys())[0]
251
+ polygon_mesh = self._get_polygon_mesh(obj_data, obj_key, vertices, min_surfaces_num)
252
+ if polygon_mesh is not None:
253
+ object_dict[obj_type][obj_ind] = polygon_mesh
254
+ return object_dict
255
+
256
+ def _read_objects_bo_em(self, dataset_config):
257
+ objects_path_dict = read_object_path_dict(dataset_config)
258
+ object_dict = defaultdict(dict)
259
+ for objects_type, objects_path in objects_path_dict.items():
260
+ file_list = [f for f in os.listdir(objects_path) if f.endswith('.json')]
261
+ for filename in file_list:
262
+ file_ind = int(filename.split('.')[0])
263
+ json_data = read_json(objects_path, file_ind)
264
+ object_dict = self._insert_polygon_mesh(object_dict, objects_type, json_data, file_ind)
265
+ object_dict[objects_type] = dict(sorted(object_dict[objects_type].items()))
266
+ return object_dict
267
+
268
+ def _read_objects_gpkg(self, dataset_config):
269
+ objects_path_dict = read_object_path_dict(dataset_config)
270
+ object_dict = defaultdict(dict)
271
+ for objects_type, objects_path in objects_path_dict.items():
272
+ file_list = [f for f in os.listdir(objects_path) if f.endswith('.json')]
273
+ for filename in file_list:
274
+ file_ind = int(filename.split('.')[0])
275
+ json_data = read_json(objects_path, file_ind)
276
+ json_data = json.loads(json_data)
277
+ object_dict = self._insert_polygon_mesh(object_dict, objects_type, json_data, file_ind)
278
+ object_dict[objects_type] = dict(sorted(object_dict[objects_type].items()))
279
+ return object_dict
280
+
281
+ def _read_objects_delivery3(self, dataset_config):
282
+ objects_path_dict = read_object_path_dict(dataset_config)
283
+ object_dict = defaultdict(dict)
284
+ mapping_dict = defaultdict(dict)
285
+ inv_mapping_dict = defaultdict(dict)
286
+ for objects_type, objects_path in objects_path_dict.items():
287
+ file_list = [f for f in os.listdir(objects_path) if f.endswith('.json')]
288
+ for file_ind, file_name in enumerate(file_list):
289
+ file_name = file_name.split('.')[0]
290
+ json_data = read_json(objects_path, file_name)
291
+ object_dict = self._insert_polygon_mesh(object_dict, objects_type, json_data, file_ind)
292
+ mapping_dict[objects_type][file_ind] = file_name
293
+ inv_mapping_dict[objects_type][file_name] = file_ind
294
+ object_dict[objects_type] = dict(sorted(object_dict[objects_type].items()))
295
+ object_dict['mapping_dict'] = mapping_dict
296
+ object_dict['inv_mapping_dict'] = inv_mapping_dict
297
+ return object_dict
298
+
299
+ def _read_objects_Hague(self, dataset_config):
300
+ """
301
+ Fallback reader used only when preprocess_hague.py has not been run.
302
+ Prefer running `python preprocess_hague.py` once to create the cache.
303
+ """
304
+ from preprocess_hague import preprocess
305
+ raw_cache_path = f"{config.FilePaths.object_dict_path}{self.dataset_name}_raw.joblib"
306
+ self.logger.info("Running preprocess_hague.preprocess() to build cache...")
307
+ return preprocess(
308
+ cands_path=dataset_config['cands_path'],
309
+ index_path=dataset_config['index_path'],
310
+ output_path=raw_cache_path,
311
+ cell_size=config.DataPartition.grid_cell_size,
312
+ min_surfaces=self.min_surfaces_num,
313
+ )
314
+
315
+ def _generate_object_dict_mappings(self, object_dict, objects_path_dict):
316
+ object_dict['mapping_dict'], object_dict['inv_mapping_dict'] = {}, {}
317
+ for object_type in objects_path_dict:
318
+ keys = list(object_dict[object_type].keys())
319
+ object_dict['mapping_dict'][object_type] = {i: k for i, k in enumerate(keys)}
320
+ object_dict['inv_mapping_dict'][object_type] = {k: i for i, k in enumerate(keys)}
321
+ return object_dict
322
+
323
+ @staticmethod
324
+ def _process_object_file(file_ind, file_path, object_type, min_surfaces_num):
325
+ print(f"Processing file {file_ind}")
326
+ with open(file_path, 'r') as f:
327
+ data = json.load(f)
328
+ vertices = data['vertices']
329
+ partial_dict = {}
330
+ for obj_key in data['CityObjects'].keys():
331
+ try:
332
+ new_obj_key = PipelineManager.standardize_obj_key(obj_key, object_type)
333
+ polygon_mesh_data = PipelineManager._get_polygon_mesh(data, obj_key, vertices,
334
+ min_surfaces_num=min_surfaces_num)
335
+ if polygon_mesh_data is not None:
336
+ partial_dict[new_obj_key] = polygon_mesh_data
337
+ except:
338
+ continue
339
+ return partial_dict
340
+
341
+ @staticmethod
342
+ def standardize_obj_key(obj_key, object_type):
343
+ if object_type == 'cands':
344
+ return obj_key.split('bag_')[1]
345
+ elif object_type == 'index':
346
+ return obj_key.split('NL.IMBAG.Pand.')[1].split('-0')[0]
347
+ else:
348
+ raise ValueError('Invalid source')
349
+
350
+ @staticmethod
351
+ def read_objects_synthetic(self, dataset_config):
352
+ pass
353
+
354
+ # def _generate_training_pairs(self):
355
+ # np.random.seed(self.seed)
356
+ # index_ids = list(self.train_object_dict['index'].keys())
357
+ # pos_pairs = [(obj_id, obj_id) for obj_id in self.train_object_dict['cands'].keys()]
358
+ # neg_pairs = [(obj_id, np.random.choice(index_ids)) for obj_id in self.train_object_dict['cands'].keys()]
359
+ # neg_pairs = [(cand_id, index_id) for cand_id, index_id in neg_pairs if cand_id != index_id]
360
+ # return pos_pairs, neg_pairs
361
+
362
+ # def _run_blocker(self):
363
+ # self.logger.info(f"Running blocking for training phase")
364
+ # dummy_feature_importance_scores = self._get_dummy_feature_importance_scores()
365
+ # dummy_property_ratios = self._get_dummy_property_ratios()
366
+ # blocker = Blocker(self.dataset_name, self.train_object_dict, self.train_property_dict,
367
+ # dummy_feature_importance_scores, dummy_property_ratios, 'bkafi', 'train')
368
+ # self.logger.info(f"The blocking process for the training phase ended successfully")
369
+ # self.train_pos_pairs_dict, self.train_neg_pairs_dict = blocker.pos_pairs_dict, blocker.neg_pairs_dict
370
+ # save_blocking_output(self.train_pos_pairs_dict, self.train_neg_pairs_dict, self.seed, self.logger, 'train')
371
+ # return
372
+
373
+ @staticmethod
374
+ def _get_dummy_feature_importance_scores():
375
+ feature_names = get_feature_name_list(config.Features.operator)
376
+ dummy_model_name = config.Models.blocking_model
377
+ return {dummy_model_name: [(feature, 1) for feature in feature_names]}
378
+
379
+ def _get_dummy_property_ratios(self):
380
+ property_ratios = {prop: {'mean': 1.0, 'std': 0.0}
381
+ for prop in self.train_property_dict.keys()}
382
+ return property_ratios
383
+
384
+ def _run_blocker(self, feature_importance_dict, train_property_ratios):
385
+ blocking_method = self.blocking_method
386
+ self.logger.info(f"Running blocking method {blocking_method}")
387
+ blocker = Blocker(self.dataset_name, self.test_object_dict, self.test_property_dict, feature_importance_dict,
388
+ train_property_ratios, self.blocking_method, self.sdr_factor, self.bkafi_criterion, 'test')
389
+ self.logger.info(f"The blocking process ended successfully")
390
+ self._save_blocking_output(blocker.pos_pairs_dict, blocker.neg_pairs_dict, blocker.blocking_execution_time)
391
+ self.blocking_result_dict = self._evaluate_blocking(blocker.pos_pairs_dict, blocker.blocking_execution_time)
392
+ return
393
+
394
+ def _run_blocker_train(self, feature_importance_dict, train_property_ratios):
395
+ blocking_method = self.blocking_method
396
+ self.logger.info(f"Running blocking method {blocking_method} for train set")
397
+ blocker = Blocker(self.dataset_name, self.train_object_dict, self.train_property_dict, feature_importance_dict,
398
+ train_property_ratios, self.blocking_method, self.sdr_factor, self.bkafi_criterion, 'test')
399
+ self.logger.info(f"The blocking process for train set ended successfully")
400
+ pos_pairs_dict, neg_pairs_dict, execution_time = (blocker.pos_pairs_dict, blocker.neg_pairs_dict,
401
+ blocker.blocking_execution_time)
402
+ self._save_blocking_output(pos_pairs_dict, neg_pairs_dict, execution_time, train_set_mode=True)
403
+ return
404
+
405
+ def _save_blocking_output(self, pos_pairs, neg_pairs, blocking_execution_time, train_set_mode=False):
406
+ blocking_dict = {'pos_pairs': pos_pairs, 'neg_pairs': neg_pairs,
407
+ 'blocking_execution_time': blocking_execution_time}
408
+ blocking_output_path = self._get_blocking_output_path()
409
+ if train_set_mode:
410
+ blocking_output_path = blocking_output_path.replace('Operator', 'Train_Operator')
411
+ try:
412
+ joblib.dump(blocking_dict, blocking_output_path)
413
+ message = f"Blocking results were saved successfully to {blocking_output_path}"
414
+ self.logger.info(message)
415
+ except Exception as e:
416
+ self.logger.error(f"Error happened while saving blocking results: {e}")
417
+ return
418
+
419
+ def _get_blocking_output_path(self):
420
+ file_name = get_file_name()
421
+ blocking_results_path = config.FilePaths.results_path + 'blocking_output/'
422
+ vector_normalization = 'True' if self.vector_normalization else 'False'
423
+ sdr_factor = 'True' if self.sdr_factor else 'False'
424
+ if not os.path.exists(blocking_results_path):
425
+ os.makedirs(blocking_results_path)
426
+ blocking_results_path = (f"{blocking_results_path}{file_name}_"
427
+ f"{self.dataset_size_version}_neg_samples_num{self.neg_samples_num}"
428
+ f"_vector_normalization_{vector_normalization}_sdr_factor_{sdr_factor}_"
429
+ f"bkafi_criterion={self.bkafi_criterion}_seed={self.seed}.joblib")
430
+ return blocking_results_path
431
+
432
+
433
+ # def _get_property_dict_path(self, train_or_test):
434
+ # file_name = get_file_name_property_dict()
435
+ # property_dict_path = config.FilePaths.property_dict_path
436
+ # vector_normalization = self.vector_normalization if self.vector_normalization is not None else 'None'
437
+ # if not os.path.exists(property_dict_path):
438
+ # os.makedirs(property_dict_path)
439
+ # property_dict_path = (f"{property_dict_path}{file_name}_{train_or_test}_{self.evaluation_mode}_"
440
+ # f"{self.dataset_size_version}_neg_samples_num={self.neg_samples_num}_"
441
+ # f"vector_normalization={vector_normalization}_seed={self.seed}.joblib")
442
+ # return property_dict_path
443
+
444
+ # def _save_blocking_evaluation(self, blocking_evaluation_dict, blocking_method_arg=None):
445
+ # file_name = get_file_name(blocking_method_arg)
446
+ # blocking_results_path = config.FilePaths.results_path
447
+ # vector_normalization = config.Features.normalization
448
+ # vector_normalization_str = vector_normalization if vector_normalization is not None else "None"
449
+ # sdr_factor = config.Blocking.sdr_factor
450
+ # sdr_factor_str = "True" if sdr_factor else "False"
451
+ # bkafi_criterion = config.Blocking.bkafi_criterion
452
+ # if not os.path.exists(blocking_results_path):
453
+ # os.makedirs(blocking_results_path)
454
+ # try:
455
+ # blocking_results_path = (f"{blocking_results_path}blocking_evaluation_results_{file_name}_"
456
+ # f"{self.dataset_size_version}_neg_samples_num{self.neg_samples_num}_"
457
+ # f"vector_normalization={vector_normalization_str}_sdr_factor_{sdr_factor_str}_"
458
+ # f"bkafi_criterion={bkafi_criterion}_seed={self.seed}.joblib")
459
+ # joblib.dump(blocking_evaluation_dict, blocking_results_path)
460
+ # self.logger.info(f"Blocking evaluation results were saved successfully")
461
+ # except Exception as e:
462
+ # self.logger.error(f"Error happened while saving blocking evaluation results: {e}")
463
+
464
+ def _evaluate_blocking(self, pos_pairs_dict, blocking_execution_time):
465
+ index_ids = set(self.test_object_dict['index'].keys())
466
+ cand_ids = set(self.test_object_dict['cands'].keys())
467
+ max_intersection = index_ids.intersection(cand_ids)
468
+ if 'bkafi' in self.blocking_method:
469
+ blocking_res_dict = self._evaluate_bkafi_blocking(max_intersection, pos_pairs_dict, blocking_execution_time)
470
+ else:
471
+ blocking_res_dict = self._evaluate_not_bkafi_blocking(max_intersection, pos_pairs_dict,
472
+ blocking_execution_time)
473
+ # self._save_blocking_evaluation(blocking_res_dict)
474
+ return blocking_res_dict
475
+
476
+ def _evaluate_bkafi_blocking(self, max_intersection, pos_pairs_dict, blocking_execution_time):
477
+ blocking_res_dict = defaultdict(dict)
478
+ for bkafi_dim in pos_pairs_dict.keys():
479
+ for cand_pairs_per_item in pos_pairs_dict[bkafi_dim].keys():
480
+ pos_pairs = set(pos_pairs_dict[bkafi_dim][cand_pairs_per_item])
481
+ blocking_recall = round(len(pos_pairs) / len(max_intersection), 3)
482
+ blocking_res_dict[bkafi_dim][cand_pairs_per_item] = {'blocking_recall': blocking_recall,
483
+ 'blocking_execution_time':
484
+ blocking_execution_time[bkafi_dim]}
485
+ if cand_pairs_per_item == 10:
486
+ self.logger.info(f"Blocking recall for {self.blocking_method}_dim {bkafi_dim} and "
487
+ f"cand_pairs_per_item {cand_pairs_per_item}: {blocking_recall}")
488
+ self.logger.info(3*'- - - - - - - - - - - - -')
489
+ return blocking_res_dict
490
+
491
+ def _evaluate_not_bkafi_blocking(self, max_intersection, pos_pairs_dict, blocking_execution_time):
492
+ blocking_res_dict = defaultdict(dict)
493
+ for cand_pairs_per_item in pos_pairs_dict.keys():
494
+ pos_pairs = set(pos_pairs_dict[cand_pairs_per_item])
495
+ blocking_recall = round(len(pos_pairs) / len(max_intersection), 3)
496
+ blocking_res_dict[cand_pairs_per_item] = {'blocking_recall': blocking_recall,
497
+ 'blocking_execution_time': blocking_execution_time}
498
+ # self.logger.info(f"Blocking recall for {self.blocking_method}, cand_pairs_per_item "
499
+ # f"{cand_pairs_per_item}: {blocking_recall}")
500
+ # self.logger.info(3*'--------------------------')
501
+ return blocking_res_dict
502
+
503
+ def _create_dataset_dict(self):
504
+ dataset_dict = self._load_dataset_dict_wrapper()
505
+ if dataset_dict is not None:
506
+ return dataset_dict
507
+ data_partition_dict, self.train_object_dict, self.test_object_dict = self._read_objects()
508
+ self.train_pos_pairs, self.train_neg_pairs = self._extract_pairs(data_partition_dict, 'train')
509
+ self.train_property_dict = self._generate_property_dict('train')
510
+ if self.evaluation_mode == "matching":
511
+ self.test_pos_pairs, self.test_neg_pairs = self._extract_pairs(data_partition_dict, 'test')
512
+ self.test_property_dict = self._generate_property_dict('test')
513
+ feature_dict = self._generate_feature_dict()
514
+ dataset_dict = self._create_final_dict(feature_dict)
515
+ return dataset_dict
516
+
517
+ def _extract_pairs(self, data_partition_dict, train_or_test):
518
+ if self.evaluation_mode == "blocking":
519
+ pair_list = data_partition_dict[train_or_test]['negative_sampling'][self.dataset_size_version] \
520
+ [self.neg_samples_num]
521
+ else:
522
+ if train_or_test == 'train':
523
+ pair_list = data_partition_dict[train_or_test][self.matching_cands_generation] \
524
+ [self.dataset_size_version][self.neg_samples_num]
525
+ else:
526
+ pair_list = data_partition_dict[train_or_test]['matching'][self.matching_cands_generation] \
527
+ [self.dataset_size_version][self.neg_samples_num]
528
+ # Same filter as _clean_object_dict_matching: drop pairs whose IDs aren't in the
529
+ # loaded object dict, so PairProcessor never sees IDs missing from property_dict.
530
+ object_dict = self.train_object_dict if train_or_test == 'train' else self.test_object_dict
531
+ avail_cands = set(object_dict['cands'].keys())
532
+ avail_index = set(object_dict['index'].keys())
533
+ before = len(pair_list)
534
+ pair_list = [p for p in pair_list if p[0] in avail_cands and p[1] in avail_index]
535
+ dropped = before - len(pair_list)
536
+ if dropped:
537
+ self.logger.info(f"_extract_pairs[{train_or_test}]: dropped {dropped}/{before} pairs "
538
+ f"with IDs not in object_dict (kept {len(pair_list)})")
539
+ pos_pairs = [pair for pair in pair_list if pair[0] == pair[1]]
540
+ neg_pairs = [pair for pair in pair_list if pair[0] != pair[1]]
541
+ return pos_pairs, neg_pairs
542
+
543
+ def _load_dataset_dict_wrapper(self):
544
+ dataset_dict = None
545
+ if config.Constants.load_dataset_dict:
546
+ dataset_dict = self._load_dataset_dict()
547
+ if dataset_dict is not None:
548
+ return dataset_dict
549
+ return dataset_dict
550
+
551
+ # def _get_pos_and_neg_pairs_for_training(self):
552
+ # bkafi_dim = min(self.train_pos_pairs_dict.keys())
553
+ # cand_pairs_per_item = min(self.test_pos_pairs_dict[bkafi_dim].keys())
554
+ # pos_pairs = self.train_pos_pairs_dict[bkafi_dim][cand_pairs_per_item]
555
+ # neg_pairs = self.train_neg_pairs_dict[bkafi_dim][cand_pairs_per_item]
556
+ # return pos_pairs, neg_pairs
557
+
558
+ # def _get_pos_and_neg_pairs(self, train_or_test):
559
+ # pos_pairs_dict = self.test_pos_pairs_dict if train_or_test == 'test' else self.train_pos_pairs_dict
560
+ # neg_pairs_dict = self.test_neg_pairs_dict if train_or_test == 'test' else self.train_neg_pairs_dict
561
+ # bkafi_dim = min(pos_pairs_dict.keys())
562
+ # cand_pairs_per_item = min(pos_pairs_dict[bkafi_dim].keys())
563
+ # pos_pairs = pos_pairs_dict[bkafi_dim][cand_pairs_per_item]
564
+ # neg_pairs = neg_pairs_dict[bkafi_dim][cand_pairs_per_item]
565
+ # return pos_pairs, neg_pairs
566
+
567
+ def _load_train_items(self):
568
+ feature_importance_dict, matching_pairs_property_ratios = None, None
569
+ try:
570
+ feature_importance_dict = load_feature_importance_dict(self.seed, self.logger)
571
+ matching_pairs_property_ratios = load_property_ratios(self.seed, self.logger)
572
+ except:
573
+ self.logger.info("Could not load training phase items. Running training phase pipeline")
574
+ return feature_importance_dict, matching_pairs_property_ratios
575
+
576
+ def _generate_property_dict(self, train_or_test):
577
+ rel_object_dict = self.train_object_dict if train_or_test == 'train' else self.test_object_dict
578
+ if config.Constants.load_property_dict:
579
+ property_dict = self._load_property_dict(train_or_test)
580
+ if property_dict is not None:
581
+ return property_dict
582
+ self.logger.info(f"Generating {train_or_test} property dictionary")
583
+ obj_property_processor = ObjectPropertiesProcessor(rel_object_dict, self.vector_normalization)
584
+ property_dict = obj_property_processor.prop_vals_dict
585
+ property_dict_generation_time = obj_property_processor.property_dict_generation_time
586
+ self.logger.info(f"Property dictionary generation time: {property_dict_generation_time}\n")
587
+ if config.Constants.save_property_dict:
588
+ self._save_property_dict(property_dict, train_or_test)
589
+ return property_dict
590
+
591
+ def _save_property_dict(self, property_dict, train_or_test):
592
+ try:
593
+ property_dict_path = self._get_property_dict_path(train_or_test)
594
+ joblib.dump(property_dict, property_dict_path)
595
+ self.logger.info(f"{train_or_test}_property_dict was saved successfully")
596
+ self.logger.info('')
597
+ except Exception as e:
598
+ self.logger.error(f"Error happened while saving {train_or_test}_property_dict: {e}")
599
+ return
600
+
601
+ def _load_property_dict(self, train_or_test):
602
+ property_dict_path = self._get_property_dict_path(train_or_test)
603
+ try:
604
+ property_dict = joblib.load(property_dict_path)
605
+ self.logger.info(f"{train_or_test}_property_dict was loaded successfully")
606
+ return property_dict
607
+ except Exception as e:
608
+ self.logger.error(f"Error happened while loading {train_or_test}_property_dict: {e}")
609
+ return None
610
+
611
+ def _get_property_dict_path(self, train_or_test):
612
+ file_name = get_file_name_property_dict()
613
+ property_dict_path = config.FilePaths.property_dict_path
614
+ vector_normalization = 'True' if self.vector_normalization else 'False'
615
+ if not os.path.exists(property_dict_path):
616
+ os.makedirs(property_dict_path)
617
+ property_dict_path = (f"{property_dict_path}{file_name}_{train_or_test}_{self.evaluation_mode}_"
618
+ f"{self.dataset_size_version}_neg_samples_num={self.neg_samples_num}_"
619
+ f"vector_normalization={vector_normalization}_seed={self.seed}.joblib")
620
+ return property_dict_path
621
+
622
+ def _generate_feature_dict(self):
623
+ feature_dict = {'train': {}, 'test': {}} if self.evaluation_mode == 'matching' else {'train': {}}
624
+ for train_or_test in feature_dict.keys():
625
+ pos_pairs, neg_pairs, property_dict = self._get_rel_pairs_and_property_dict(train_or_test)
626
+ self.logger.info(f"Generating {train_or_test} feature vectors")
627
+ for label, pairs_list in zip([0, 1], [neg_pairs, pos_pairs]):
628
+ feature_dict[train_or_test][label] = PairProcessor(property_dict, pairs_list).feature_vec
629
+ return feature_dict
630
+
631
+ def _get_rel_pairs_and_property_dict(self, train_or_test):
632
+ if train_or_test == 'train':
633
+ pos_pairs, neg_pairs = self.train_pos_pairs, self.train_neg_pairs
634
+ property_dict = self.train_property_dict
635
+ else:
636
+ pos_pairs, neg_pairs = self.test_pos_pairs, self.test_neg_pairs
637
+ property_dict = self.test_property_dict
638
+ return pos_pairs, neg_pairs, property_dict
639
+
640
+ def _create_final_dict(self, feature_dict):
641
+ np.random.seed(self.seed)
642
+ dataset_dict = {'train': {}, 'test': {}} if self.evaluation_mode == 'matching' else {'train': {}}
643
+ for train_or_test in dataset_dict.keys():
644
+ merged_features, merged_labels = self._merge_features_and_labels(feature_dict, train_or_test)
645
+ if train_or_test == 'test' and self.evaluation_mode == 'matching':
646
+ # Store pair IDs alongside X/Y so alignment can map scores to building IDs
647
+ merged_pairs = self.test_neg_pairs + self.test_pos_pairs
648
+ dataset_dict = self._prepare_dataset(dataset_dict, train_or_test,
649
+ merged_features, merged_labels,
650
+ merged_pairs=merged_pairs)
651
+ else:
652
+ dataset_dict = self._prepare_dataset(dataset_dict, train_or_test,
653
+ merged_features, merged_labels)
654
+ if config.Constants.save_dataset_dict:
655
+ self._save_dataset_dict(dataset_dict)
656
+ return dataset_dict
657
+
658
+ def _save_dataset_dict(self, dataset_dict):
659
+ dataset_dict_path = self._get_dataset_dict_path()
660
+ saving_message = f"dataset_dict was saved successfully"
661
+ error_message = f"Error happened while saving dataset_dict: "
662
+ try:
663
+ joblib.dump(dataset_dict, dataset_dict_path)
664
+ self.logger.info(saving_message)
665
+ self.logger.info('')
666
+ except Exception as e:
667
+ self.logger.error(f"{error_message}{e}")
668
+ return
669
+
670
+ def _load_dataset_dict(self):
671
+ dataset_dict_path = self._get_dataset_dict_path()
672
+ try:
673
+ dataset_dict = joblib.load(dataset_dict_path)
674
+ self.logger.info(f"dataset_dict was loaded successfully")
675
+ return dataset_dict
676
+ except Exception as e:
677
+ self.logger.error(f"Error happened while loading dataset_dict: {e}")
678
+ return None
679
+
680
+ def _get_dataset_dict_path(self):
681
+ dataset_dict_dir = config.FilePaths.dataset_dict_path
682
+ file_name = get_file_name()
683
+ if not os.path.exists(dataset_dict_dir):
684
+ os.makedirs(dataset_dict_dir)
685
+ dataset_dict_path = (f"{dataset_dict_dir}{file_name}_{self.evaluation_mode}_{self.dataset_size_version}_"
686
+ f"neg_samples={self.neg_samples_num}_seed={self.seed}.joblib")
687
+ return dataset_dict_path
688
+
689
+ def _merge_features_and_labels(self, feature_dict, train_or_test):
690
+ neg_feature_vecs, pos_feature_vecs = feature_dict[train_or_test][0], feature_dict[train_or_test][1]
691
+ merged_features = neg_feature_vecs + pos_feature_vecs
692
+ merged_labels = [0] * len(neg_feature_vecs) + [1] * len(pos_feature_vecs)
693
+ return merged_features, merged_labels
694
+
695
+ @staticmethod
696
+ def _prepare_dataset(dataset_dict, file_type, merged_features, merged_labels,
697
+ merged_pairs=None):
698
+ """
699
+ Shuffle features/labels (and optionally pair IDs) together and store in dataset_dict.
700
+
701
+ merged_pairs : list of (cand_id, index_id), parallel to merged_features.
702
+ When provided, dataset_dict[file_type]['pairs'] is stored in the same
703
+ shuffled order as X/Y — required for mapping classifier scores back to
704
+ building IDs in the alignment step.
705
+ """
706
+ if merged_pairs is not None:
707
+ combined = list(zip(merged_features, merged_labels, merged_pairs))
708
+ np.random.shuffle(combined)
709
+ dataset_dict[file_type]['X'] = np.array([e[0] for e in combined])
710
+ dataset_dict[file_type]['Y'] = np.array([e[1] for e in combined])
711
+ dataset_dict[file_type]['pairs'] = [e[2] for e in combined]
712
+ else:
713
+ combined = list(zip(merged_features, merged_labels))
714
+ np.random.shuffle(combined)
715
+ dataset_dict[file_type]['X'] = np.array([e[0] for e in combined])
716
+ dataset_dict[file_type]['Y'] = np.array([e[1] for e in combined])
717
+ return dataset_dict
718
+
719
+ def _train_and_evaluate(self, ):
720
+ if self.evaluation_mode == 'blocking':
721
+ feature_importance_dict, train_property_ratios = self._train_for_blocking()
722
+ if self.run_blocker_train:
723
+ self._run_blocker_train(feature_importance_dict, train_property_ratios)
724
+ else:
725
+ self._run_blocker(feature_importance_dict, train_property_ratios)
726
+ flexible_classifier = None
727
+ else:
728
+ flexible_classifier = self._run_matching_pipeline()
729
+ self._run_alignment(flexible_classifier)
730
+ return flexible_classifier
731
+
732
+ def _run_alignment(self, flexible_classifier_obj):
733
+ """
734
+ Stage 4: Estimate rigid 3D transform from high-confidence matches and
735
+ re-score all test pairs combining geometric + spatial proximity.
736
+
737
+ Requires:
738
+ - evaluation_mode == 'matching'
739
+ - dataset_dict['test']['pairs'] populated by _create_final_dict
740
+ - config.Alignment.enabled == True
741
+ """
742
+ if not config.Alignment.enabled:
743
+ return
744
+ if flexible_classifier_obj is None:
745
+ return
746
+ test_split = self.dataset_dict.get('test', {})
747
+ if 'pairs' not in test_split:
748
+ self.logger.warning("[_run_alignment] No pair IDs in dataset_dict['test']. "
749
+ "Ensure load_dataset_dict=False so pairs are freshly built.")
750
+ return
751
+
752
+ # Pick the primary model for scoring
753
+ model_name = config.Models.model_to_use
754
+ if model_name not in flexible_classifier_obj.best_model_dict:
755
+ model_name = next(iter(flexible_classifier_obj.best_model_dict))
756
+ best_model = flexible_classifier_obj.best_model_dict[model_name]['model']
757
+
758
+ X_test = test_split['X']
759
+ pairs = test_split['pairs'] # list of (cand_id, index_id), same shuffle order as X
760
+
761
+ # Geometric scores: P(match=1)
762
+ proba = best_model.predict_proba(X_test)
763
+ match_class_idx = list(best_model.classes_).index(1)
764
+ geo_scores = proba[:, match_class_idx]
765
+
766
+ scored_pairs = [(cid, iid, float(s)) for (cid, iid), s in zip(pairs, geo_scores)]
767
+
768
+ self.logger.info(
769
+ f"[_run_alignment] {len(scored_pairs)} test pairs | "
770
+ f"model={model_name} | "
771
+ f"anchors with score>={config.Alignment.confidence_threshold}: "
772
+ f"{sum(1 for _,_,s in scored_pairs if s >= config.Alignment.confidence_threshold)}"
773
+ )
774
+
775
+ aligner = RigidAligner(config.Alignment, logger=self.logger)
776
+ ground_truth_R = getattr(self._simulator, 'R_crs', None)
777
+ ground_truth_t = getattr(self._simulator, 't_crs', None)
778
+
779
+ rescored_pairs = aligner.run(
780
+ self.test_object_dict,
781
+ scored_pairs,
782
+ suffix=f"seed{self.seed}",
783
+ ground_truth_R=ground_truth_R,
784
+ ground_truth_t=ground_truth_t,
785
+ )
786
+
787
+ # Log final score improvement summary
788
+ if aligner.alignment_succeeded:
789
+ top_geo = sorted(scored_pairs, key=lambda x: x[2], reverse=True)[:10]
790
+ top_final = sorted(rescored_pairs, key=lambda x: x[2], reverse=True)[:10]
791
+ self.logger.info(
792
+ f"[_run_alignment] Top-10 mean geometric score: "
793
+ f"{np.mean([s for _,_,s in top_geo]):.3f} → "
794
+ f"final score: {np.mean([s for _,_,s in top_final]):.3f}"
795
+ )
796
+
797
+ # Precision / Recall / F1 before and after alignment
798
+ self._log_alignment_metrics(scored_pairs, rescored_pairs, self.test_object_dict)
799
+
800
+ def _log_alignment_metrics(self, scored_pairs, rescored_pairs, test_object_dict,
801
+ score_threshold=0.5, dist_thresholds=(10.0, 25.0, 50.0)):
802
+ """
803
+ Log two sets of metrics:
804
+
805
+ 1. Score-based (before alignment only) — classifier Precision/Recall/F1
806
+ at score_threshold. Measures how well the geometric features identify matches.
807
+
808
+ 2. Distance-based (after alignment) — for each matched candidate, check whether
809
+ its aligned centroid is within dist_threshold meters of its true match centroid.
810
+ This is the correct evaluation after alignment: if the transform is good,
811
+ every candidate should be physically co-located with its match.
812
+
813
+ Note: candidates with no true match in the index are never counted as false
814
+ negatives — recall is only over the intersection (buildings with a real match).
815
+ """
816
+ # --- 1. Score-based metrics (before alignment) ---
817
+ def _prf(pairs):
818
+ tp = sum(1 for cid, iid, s in pairs if s >= score_threshold and cid == iid)
819
+ fp = sum(1 for cid, iid, s in pairs if s >= score_threshold and cid != iid)
820
+ fn = sum(1 for cid, iid, s in pairs if s < score_threshold and cid == iid)
821
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
822
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
823
+ f1 = (2 * precision * recall / (precision + recall)
824
+ if (precision + recall) > 0 else 0.0)
825
+ return round(precision, 3), round(recall, 3), round(f1, 3)
826
+
827
+ pre_p, pre_r, pre_f1 = _prf(scored_pairs)
828
+ self.logger.info(
829
+ f"[Metrics] Before alignment (score≥{score_threshold}) — "
830
+ f"Precision: {pre_p} Recall: {pre_r} F1: {pre_f1}"
831
+ )
832
+
833
+ # --- 2. Distance-based metrics (after alignment) ---
834
+ # After alignment, test_object_dict['cands'] centroids are already transformed.
835
+ # True matches are pairs where cand_id == index_id.
836
+ cands = test_object_dict.get('cands', {})
837
+ index = test_object_dict.get('index', {})
838
+ # All matched cands (ground truth positives in the test set)
839
+ matched_cands = {cid for cid, iid, _ in scored_pairs if cid == iid and cid in cands and iid in index}
840
+ n_matched = len(matched_cands)
841
+
842
+ if n_matched == 0:
843
+ self.logger.warning("[Metrics] No matched pairs found for distance evaluation.")
844
+ return
845
+
846
+ # Compute distance from each aligned cand centroid to its true match index centroid
847
+ distances = []
848
+ for cid in matched_cands:
849
+ c_centroid = np.asarray(cands[cid]['centroid'], dtype=np.float64)
850
+ i_centroid = np.asarray(index[cid]['centroid'], dtype=np.float64)
851
+ distances.append(np.linalg.norm(c_centroid - i_centroid))
852
+
853
+ distances = np.array(distances)
854
+ self.logger.info(
855
+ f"[Metrics] After alignment (distance-based, n={n_matched} matched buildings) — "
856
+ f"mean dist: {distances.mean():.1f} m | "
857
+ f"median dist: {np.median(distances):.1f} m | "
858
+ f"max dist: {distances.max():.1f} m"
859
+ )
860
+ for d_thresh in dist_thresholds:
861
+ recall_d = round((distances < d_thresh).sum() / n_matched, 3)
862
+ self.logger.info(
863
+ f"[Metrics] After alignment distance recall@{d_thresh:.0f}m: {recall_d} "
864
+ f"({(distances < d_thresh).sum()}/{n_matched} buildings within {d_thresh:.0f} m of true match)"
865
+ )
866
+
867
+ def _train_for_blocking(self):
868
+ self.logger.info("Training for blocking")
869
+ if config.Constants.load_train_items:
870
+ feature_importance_dict, matching_pairs_property_ratios = self._load_train_items()
871
+ if feature_importance_dict is not None and matching_pairs_property_ratios is not None:
872
+ return feature_importance_dict, matching_pairs_property_ratios
873
+ params_dict = self._read_config_models()
874
+ load_trained_models = config.Models.load_trained_models
875
+ cv = config.Models.cv
876
+ flexible_classifier_obj = FlexibleClassifier(self.dataset_dict, self.train_property_dict, params_dict,
877
+ self.seed, self.logger, self.dataset_name, 'blocking',
878
+ self.dataset_size_version, self.neg_samples_num,
879
+ load_trained_models, cv)
880
+ feature_importance_dict = flexible_classifier_obj.feature_importance_extraction()
881
+ train_property_ratios = flexible_classifier_obj.get_property_ratios()
882
+ return feature_importance_dict, train_property_ratios
883
+
884
+ def _run_matching_pipeline(self):
885
+ self.logger.info("Training for matching")
886
+ params_dict = self._read_config_models()
887
+ load_trained_models = config.Models.load_trained_models
888
+ cv = config.Models.cv
889
+ flexible_classifier_obj = FlexibleClassifier(self.dataset_dict, None, params_dict, self.seed, self.logger,
890
+ self.dataset_name, 'matching', self.dataset_size_version,
891
+ self.neg_samples_num, load_trained_models, cv)
892
+ return flexible_classifier_obj
893
+
894
+
895
+ def _read_config_models(self):
896
+ model_list = config.Models.model_list if self.evaluation_mode == 'matching' else [config.Models.blocking_model]
897
+ params_dict = dict()
898
+ for model in model_list:
899
+ params_dict[model] = config.Models.params_dict[model]
900
+ return params_dict
901
+
902
+ def _get_result_dict(self):
903
+ if self.evaluation_mode == 'blocking':
904
+ if self.run_blocker_train:
905
+ return None
906
+ return {'blocking': self.blocking_result_dict}
907
+ elif self.evaluation_mode == 'matching':
908
+ return {'matching': self.flexible_classifier_obj.result_dict}
909
+ else:
910
+ raise ValueError(f"Evaluation mode {self.evaluation_mode} is not supported")
code/3dSAGER/requirements.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 3dSAGER — Python 3.9
2
+ # Install with: pip install -r requirements.txt
3
+ # Note: faiss should be installed via conda: conda install -c conda-forge faiss-cpu
4
+
5
+ # Core ML / data
6
+ numpy==1.26.4
7
+ pandas==2.3.2
8
+ scikit-learn==1.6.1
9
+ xgboost==2.1.4
10
+ scipy==1.13.1
11
+ joblib==1.5.2
12
+
13
+ # Geometry / GIS
14
+ shapely==2.0.5
15
+ pyproj==3.6.1
16
+ geopandas==0.14.4
17
+
18
+ # Visualisation
19
+ matplotlib==3.9.2
20
+
21
+ # Utilities
22
+ tqdm==4.67.1
23
+ Pillow==9.4.0
24
+
25
+ # Vector search (install via conda for best performance)
26
+ # conda install -c conda-forge faiss-cpu
27
+ # pip fallback:
28
+ faiss-cpu==1.9.0
29
+
30
+ # Deep learning (optional — required only for ViT-based blocking)
31
+ torch==2.5.1
32
+ torchvision==0.20.1
33
+ # CLIP (OpenAI):
34
+ # pip install git+https://github.com/openai/CLIP.git
35
+
36
+ # Optional — CityGML utilities (generateCityGML.py, randomiseCity.py only)
37
+ # lxml>=4.9
38
+
39
+ clip
40
+ pyarrow
docs/STEM_benchmark_specification.md ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # STEM: Spatio-Temporal 3D Entity Matching Benchmark
2
+
3
+ ## Construction Specification Document
4
+
5
+ **Version**: 1.0
6
+ **Date**: 2026-07-08
7
+ **Authors**: ZRH Edu
8
+ **Target Venue**: VLDB Journal Special Issue on "Spatio-Temporal Data Management and Analytics: Machine Learning-based Solutions and Beyond"
9
+ **HuggingFace Repository**: https://huggingface.co/datasets/eduzrh/STEM
10
+
11
+ ---
12
+
13
+ ## Table of Contents
14
+
15
+ 1. [Project Overview](#1-project-overview)
16
+ 2. [Research Motivation](#2-research-motivation)
17
+ 3. [Dataset Sources](#3-dataset-sources)
18
+ 4. [Benchmark Design](#4-benchmark-design)
19
+ 5. [Code Architecture](#5-code-architecture)
20
+ 6. [Environment Setup](#6-environment-setup)
21
+ 7. [Download Plan](#7-download-plan)
22
+ 8. [Preprocessing Pipeline](#8-preprocessing-pipeline)
23
+ 9. [Experimental Protocol](#9-experimental-protocol)
24
+ 10. [Delivery Checklist](#10-delivery-checklist)
25
+
26
+ ---
27
+
28
+ ## 1. Project Overview
29
+
30
+ ### 1.1 Goal
31
+
32
+ Build the first **spatio-temporal 3D entity matching benchmark** that enables rigorous evaluation of matching algorithms for 3D building objects across both **different data sources** (cross-source entity resolution) and **different time points** (temporal entity resolution). The benchmark is designed to support both **unsupervised** and **few-shot** entity matching paradigms.
33
+
34
+ ### 1.2 Core Contributions
35
+
36
+ | Contribution | Description |
37
+ |---|---|
38
+ | **STEM-3D Benchmark** | Multi-epoch, multi-source 3D building entity matching dataset with ground-truth labels |
39
+ | **Disaster Simulation Pipeline** | Controllable CRS misalignment + structural damage for realistic post-disaster cross-time matching |
40
+ | **Spatio-Temporal Evaluation Suite** | Standardized metrics for cross-time, cross-source 3D entity matching |
41
+ | **Open-Source Toolkit** | Full codebase for reproduction, extending 3dSAGER to spatio-temporal setting |
42
+
43
+ ### 1.3 Why 3D Entity Matching Matters
44
+
45
+ Traditional entity matching (EM) operates on tabular records. However, real-world geospatial entities — buildings, bridges, infrastructure — are inherently 3D objects. Matching them across datasets is critical for:
46
+
47
+ - **Disaster response**: Match pre-disaster and post-disaster building inventories to assess damage
48
+ - **Urban digital twins**: Fuse multi-source 3D city models (Overture, 3DBAG, OpenStreetMap, commercial providers)
49
+ - **Cadastral reconciliation**: Match building registrations across jurisdictions and over time
50
+ - **Infrastructure monitoring**: Track structural changes across satellite/airborne LiDAR surveys
51
+
52
+ The **spatio-temporal** dimension adds unique challenges:
53
+ 1. Buildings can be **modified** (extensions, demolitions, renovations) between time points
54
+ 2. CRS (Coordinate Reference System) may differ between sources and epochs
55
+ 3. Geometric properties change with time (height reduction from damage, volume changes from extensions)
56
+ 4. No absolute coordinate alignment is available (post-disaster scenario)
57
+
58
+ ---
59
+
60
+ ## 2. Research Motivation
61
+
62
+ ### 2.1 The Spatio-Temporal Entity Matching Problem
63
+
64
+ **Definition (Strong Spatio-Temporal EM)**: Given two collections of 3D building objects S_A_t and S_B_t' from potentially different sources A, B and different time points t, t', find all matching pairs (a in S_A_t, b in S_B_t') where a and b refer to the same real-world building.
65
+
66
+ **Key differences from standard EM**:
67
+ 1. **Coordinate-unaware matching**: Cannot rely on absolute coordinates (different CRS, post-disaster shift)
68
+ 2. **Temporal geometry drift**: Properties change between t and t' → geometric feature ratios deviate from 1.0
69
+ 3. **Structural emergence/disappearance**: New buildings appear, old buildings are demolished
70
+ 4. **Cross-source schema heterogeneity**: Different LOD levels, attribute schemas, modeling conventions
71
+
72
+ ### 2.2 The (ε, δ)-Systematic Discrepancy Framework
73
+
74
+ Following the 3dSAGER paper, we formalize cross-source systematic discrepancy:
75
+
76
+ > For any geometric property p, there exists a source-specific scaling factor F_S^p such that for all matching buildings:
77
+ > p_cand / p_index ≈ F_S^p
78
+
79
+ In the spatio-temporal setting, we extend this to:
80
+
81
+ > p_cand_t' / p_index_t ≈ F_S^p · F_T^p
82
+
83
+ where F_S^p is the source discrepancy and F_T^p is the temporal change factor.
84
+
85
+ ### 2.3 Methodological Approach
86
+
87
+ We adopt and extend the **3dSAGER pipeline** for spatio-temporal entity matching:
88
+
89
+ Raw 3D City Models (CityJSON/CityGML) → Preprocessing → Object Properties (25 geometric features) → Pairwise Feature Vectors (F÷ division operator) → BKAFI Blocking → ML Classifier (XGBoost, RF, etc.) → Rigid Alignment (RANSAC + SVD) → Final Matching
90
+
91
+ **Key extensions for spatio-temporal**:
92
+ 1. **Temporal property delta features**: Δp = |p_t' - p_t| as additional features
93
+ 2. **Disaster-aware CRS simulation**: Random Z-rotation + damage (height reduction) for post-disaster scenarios
94
+ 3. **Multi-epoch evaluation**: Match across (t=2009, t'=2012/2015/2018) pairs
95
+ 4. **(ε, δ)-Temporal discrepancy tracking**: Measure F_T^p for each time gap
96
+ ## 3. Dataset Sources
97
+
98
+ ### 3.1 Primary Dataset: Lyon Multi-Epoch 3D City Model
99
+
100
+ **Source**: Métropole de Lyon Open Data + Zenodo
101
+ **Format**: CityGML LOD2
102
+ **Temporal coverage**: 2009, 2012, 2015, 2018 (4 epochs, 9-year span)
103
+ **Coverage**: Lyon metropolitan area (59 communes)
104
+ **Key features**:
105
+ - Same source/provider across all epochs (minimizes cross-source artifacts)
106
+ - Known to contain real building changes (demolitions, new constructions, renovations)
107
+ - Already used in 3D change detection research
108
+ - CityGML format with semantic building parts
109
+
110
+ | Epoch | Source | URL | Status |
111
+ |---|---|---|---|
112
+ | 2009 | Zenodo | https://zenodo.org/record/3611354 | Open access |
113
+ | 2012 | Zenodo | https://zenodo.org/record/3611354 | Open access |
114
+ | 2015 | Zenodo | https://zenodo.org/record/3611354 | Open access |
115
+ | 2018 | Grand Lyon Portal | https://data.grandlyon.com | Open access |
116
+
117
+ **Data characteristics**:
118
+ - CRS: EPSG:3946 (RGF93 / CC46)
119
+ - LOD: LOD2 (buildings with roof geometry, no detailed facade elements)
120
+ - Format: CityGML 2.0
121
+ - Estimated building count: ~150,000–200,000 per epoch
122
+
123
+ ### 3.2 Secondary Dataset: 3dSAGER Hague Benchmark
124
+
125
+ **Source**: 3dSAGER project
126
+ **Format**: CityJSON
127
+ **Provider**: 3D BAG (Netherlands)
128
+ **Coverage**: The Hague, Netherlands
129
+ **Temporal**: Single epoch (2021/2022) with two co-registered sources (Source A, Source B)
130
+ **URL**: https://tinyurl.com/3dSAGERdataset
131
+ **Key features**:
132
+ - Provides **ground-truth match labels** across Source A/B
133
+ - Two sources with different LOD representations of the same area
134
+ - Used as baseline for cross-source evaluation (matching mode)
135
+
136
+ **Benchmark statistics** (medium version):
137
+ - ~3,000–5,000 buildings
138
+ - 25 geometric properties per building
139
+ - Train/val/test split by spatial grid cells
140
+
141
+ ### 3.3 Temporal POI Data (Auxiliary)
142
+
143
+ **Source**: OpenStreetMap History API
144
+ **Purpose**: Ground-truth verification for POI-level temporal entity matching
145
+ **Entities**: Restaurants, shops, offices with temporal change logs
146
+ **Temporal resolution**: Daily snapshots
147
+ **Usage**: Validate temporal matching methodology at smaller scale
148
+
149
+ ### 3.4 Dataset Summary Table
150
+
151
+ | Dataset | Type | Buildings | Epochs | LOD | Format | Labels |
152
+ |---|---|---|---|---|---|---|
153
+ | Lyon 2009–2018 | Primary | ~150K/epoch | 4 | LOD2 | CityGML | Build from persistence |
154
+ | Hague A/B | Baseline | ~4K | 1 (2 sources) | LOD1/LOD2 | CityJSON | Provided |
155
+ | OSM POI History | Auxiliary | ~5K POIs | Daily | N/A | GeoJSON | OSM IDs |
156
+
157
+ ---
158
+
159
+ ## 4. Benchmark Design
160
+
161
+ ### 4.1 Task Taxonomy
162
+
163
+ The STEM benchmark defines **three sub-tasks**:
164
+
165
+ #### Task 1: Cross-Source 3D Entity Matching (Standard)
166
+ - **Input**: Source A buildings + Source B buildings (same epoch, different providers)
167
+ - **Goal**: Match corresponding buildings
168
+ - **Baseline dataset**: Hague A/B
169
+ - **Difficulty**: Cross-source schema heterogeneity (LOD differences)
170
+
171
+ #### Task 2: Cross-Time 3D Entity Matching (Temporal)
172
+ - **Input**: Buildings from epoch t + buildings from epoch t' (t ≠ t', same provider)
173
+ - **Goal**: Match persistent buildings across time
174
+ - **Primary dataset**: Lyon 2009–2018 (6 time pairs: 2009→2012, 2009→2015, 2009→2018, 2012→2015, 2012→2018, 2015→2018)
175
+ - **Difficulty**: Temporal geometry drift, building modifications, demolitions/new constructions
176
+
177
+ #### Task 3: Cross-Source + Cross-Time 3D Entity Matching (Full ST-EM)
178
+ - **Input**: Source A at epoch t + Source B at epoch t'
179
+ - **Goal**: Match buildings across both source and time
180
+ - **Constructed via**: Apply disaster simulation (CRS + damage) to cross-time pairs
181
+ - **Difficulty**: Maximum — both source and temporal discrepancies compound
182
+
183
+ ### 4.2 Ground-Truth Label Construction
184
+
185
+ For the Lyon multi-epoch dataset, we construct ground-truth labels as follows:
186
+
187
+ 1. **Spatial persistence filter**: Buildings with centroid distance < 2m across epochs are candidates
188
+ 2. **Geometric consistency check**: Area ratio and volume ratio within [0.7, 1.3] → likely same building
189
+ 3. **Building ID tracking**: Use CityGML `gml:id` attributes where available (Lyon may have persistent IDs)
190
+ 4. **Manual sampling verification**: Random sample of 200 pairs per epoch gap for manual validation
191
+ 5. **Confidence tiers**:
192
+ - **High confidence**: Persistent CityGML ID + geometric consistency
193
+ - **Medium confidence**: Spatial + geometric consistency only
194
+ - **Low confidence**: Spatial proximity only (for hard negative mining)
195
+
196
+ ### 4.3 Evaluation Metrics
197
+
198
+ | Metric | Description |
199
+ |---|---|
200
+ | **Precision** | TP / (TP + FP) |
201
+ | **Recall** | TP / (TP + FN) |
202
+ | **F1-Score** | Harmonic mean of Precision and Recall |
203
+ | **Recall@k** | Recall within top-k candidates per query building |
204
+ | **MRR** | Mean Reciprocal Rank |
205
+ | **Distance Recall** | Recall at spatial distance thresholds (10m, 25m, 50m) |
206
+ | **Temporal F1 Drop** | F1 degradation as time gap increases |
207
+ | **Cross-Source F1 Drop** | F1 degradation from single-source to cross-source matching |
208
+ | **Cross-Time F1 Drop** | F1 degradation from single-epoch to cross-epoch matching |
209
+
210
+ ### 4.4 Training Regime Taxonomy
211
+
212
+ | Regime | Training Data | Test Data | Setting |
213
+ |---|---|---|---|
214
+ | **Supervised** | Labeled pairs from t→t' | Held-out pairs from same t→t' | Full labels available |
215
+ | **Few-shot** | K labeled pairs (K=5,10,20,50) | All remaining pairs | Scarce supervision |
216
+ | **Unsupervised (Zero-shot)** | No labels from target pair | All pairs from t→t' | Cross-epoch generalization |
217
+ | **Cross-epoch transfer** | Train on t1→t2, test on t3→t4 | Transfer to unseen epochs | Temporal generalization |
218
+ | **Cross-city transfer** | Train on Hague, test on Lyon | Transfer to unseen city | Geographic generalization |
219
+
220
+ ### 4.5 Benchmark Splits
221
+
222
+ ```
223
+ STEM/
224
+ ├── lyon/
225
+ │ ├── 2009/, 2012/, 2015/, 2018/ # CityJSON-converted buildings
226
+ │ ├── labels/ # Ground-truth match pairs per epoch pair
227
+ │ └── splits/ # train/val/test CSV files
228
+ ├── hague/
229
+ │ ├── source_a/, source_b/
230
+ │ ├── labels.csv
231
+ │ └── splits/
232
+ ├── disaster/
233
+ │ ├── simulated/ # Disaster simulation outputs
234
+ │ └── configs/ # Simulation parameters
235
+ └── metadata/
236
+ ├── dataset_card.md
237
+ ├── statistics.json
238
+ └── changelog.md
239
+ ```
240
+ ## 5. Code Architecture
241
+
242
+ ### 5.1 Repository Structure
243
+
244
+ ```
245
+ STEM/
246
+ ├── README.md
247
+ ├── requirements.txt
248
+ ├── setup.py
249
+ ├── config/
250
+ │ ├── default.yaml # Default configuration
251
+ │ ├── lyon.yaml # Lyon-specific config
252
+ │ ├── hague.yaml # Hague-specific config
253
+ │ └── disaster.yaml # Disaster simulation config
254
+ ├── src/
255
+ │ ├── __init__.py
256
+ │ ├── data/
257
+ │ │ ├── __init__.py
258
+ │ │ ├── download.py # Dataset downloader
259
+ │ │ ├── preprocess.py # CityJSON/GML conversion
260
+ │ │ ├── labels.py # Ground-truth label construction
261
+ │ │ └── splits.py # Train/val/test splitting
262
+ │ ├── features/
263
+ │ │ ├── __init__.py
264
+ │ │ ├── properties.py # 3dSAGER geometric properties (extended)
265
+ │ │ ├── temporal.py # Temporal delta features
266
+ │ │ └── pairwise.py # Pairwise feature vectors
267
+ │ ├── matching/
268
+ │ │ ├── __init__.py
269
+ │ │ ├── blocking.py # BKAFI + extended blocking methods
270
+ │ │ ├── classifier.py # ML classifier training
271
+ │ │ ├── alignment.py # RANSAC rigid alignment
272
+ │ │ └── disaster.py # Disaster simulation
273
+ │ ├── evaluation/
274
+ │ │ ├── __init__.py
275
+ │ │ ├── metrics.py # Evaluation metrics
276
+ │ │ ├── analysis.py # Result analysis utilities
277
+ │ │ └── visualization.py # Plots and reports
278
+ │ └── utils/
279
+ │ ├── __init__.py
280
+ │ ├── io.py # File I/O utilities
281
+ │ ├── geometry.py # Geometric computation helpers
282
+ │ └── logging.py # Experiment logging
283
+ ├── experiments/
284
+ │ ├── baseline_hague.py # Reproduce 3dSAGER baseline
285
+ │ ├── cross_time_lyon.py # Cross-time matching experiments
286
+ │ ├── few_shot_benchmark.py # Few-shot evaluation
287
+ │ ├── zero_shot_benchmark.py # Unsupervised/zero-shot evaluation
288
+ │ └── disaster_scenario.py # Post-disaster matching
289
+ ├── notebooks/
290
+ │ ├── 01_data_exploration.ipynb
291
+ │ ├── 02_feature_analysis.ipynb
292
+ │ └── 03_results_visualization.ipynb
293
+ ├── tests/
294
+ │ ├── test_properties.py
295
+ │ ├── test_blocking.py
296
+ │ └── test_labels.py
297
+ └── docs/
298
+ ├── api.md
299
+ ├── benchmark_guide.md
300
+ └── paper_figures/
301
+ ```
302
+
303
+ ### 5.2 Key Design Decisions
304
+
305
+ 1. **CityJSON as canonical format**: All datasets converted to CityJSON v1.1 for uniformity
306
+ 2. **Modular experiment scripts**: Each experiment type is a standalone script with YAML config
307
+ 3. **Reproducibility**: All random seeds logged; configs versioned with experiment outputs
308
+ 4. **HuggingFace Hub integration**: `push_to_hub()` calls in all data generation scripts
309
+ 5. **Streaming support**: Large CityJSON files use streaming parsing (ijson)
310
+
311
+ ### 5.3 Extension Points
312
+
313
+ | Extension | Location | Purpose |
314
+ |---|---|---|
315
+ | New dataset | `src/data/preprocess.py` | Add CityJSON conversion for new cities |
316
+ | New feature | `src/features/properties.py` | Add geometric/temporal property |
317
+ | New blocking method | `src/matching/blocking.py` | Add candidate generation method |
318
+ | New classifier | `src/matching/classifier.py` | Add ML/DL model |
319
+ | New evaluation metric | `src/evaluation/metrics.py` | Add custom metric |
320
+
321
+ ---
322
+
323
+ ## 6. Environment Setup
324
+
325
+ ### 6.1 Python Environment
326
+
327
+ ```bash
328
+ # Core environment
329
+ Python 3.9+ (tested with 3.9–3.12)
330
+ pip install -r requirements.txt
331
+
332
+ # Key dependencies (all installed via pip):
333
+ numpy==1.26.4
334
+ pandas==2.3.2
335
+ scikit-learn==1.6.1
336
+ xgboost==2.1.4
337
+ shapely==2.0.5
338
+ pyproj==3.6.1
339
+ geopandas==0.14.4
340
+ faiss-cpu==1.9.0
341
+ scipy==1.13.1
342
+ joblib==1.5.2
343
+ matplotlib==3.9.2
344
+ tqdm==4.67.1
345
+
346
+ # Optional — PyTorch + CLIP (for ViT-based blocking):
347
+ torch>=2.0.0
348
+ torchvision>=0.15.0
349
+ clip (from OpenAI GitHub)
350
+
351
+ # HuggingFace:
352
+ huggingface_hub>=0.20.0
353
+ datasets>=2.14.0
354
+ ```
355
+
356
+ ### 6.2 Disk Space Requirements
357
+
358
+ | Item | Estimated Size |
359
+ |---|---|
360
+ | Lyon 2009 CityGML | ~2–5 GB (compressed) |
361
+ | Lyon 2012 CityGML | ~2–5 GB (compressed) |
362
+ | Lyon 2015 CityGML | ~2–5 GB (compressed) |
363
+ | Lyon 2018 CityGML | ~2–5 GB (compressed) |
364
+ | Hague benchmark (A + B) | ~500 MB |
365
+ | Processed CityJSON files | ~2–3 GB per epoch |
366
+ | Feature caches (joblib) | ~200 MB per epoch |
367
+ | Model files | ~50 MB |
368
+ | **Total estimated** | **~25–40 GB** |
369
+
370
+ ## 7. Download Plan
371
+
372
+ ### 7.1 Step-by-Step Download Procedure
373
+
374
+ #### Phase 1: Hague Baseline Dataset (Priority: HIGH)
375
+
376
+ The 3dSAGER dataset contains The Hague buildings in CityJSON format, split into Source A and Source B directories. This is the baseline benchmark used in the 3dSAGER paper.
377
+
378
+ URL: https://tinyurl.com/3dSAGERdataset
379
+ Expected output: data/hague/source_a/*.json, data/hague/source_b/*.json
380
+
381
+ #### Phase 2: Lyon Multi-Epoch Dataset (Priority: HIGH)
382
+
383
+ **Lyon 2009, 2012, 2015 from Zenodo**: https://zenodo.org/record/3611354
384
+ Contains CityGML files for Lyon arrondissements across three historic versions.
385
+
386
+ **Lyon 2018 from Grand Lyon Portal**:
387
+ https://data.grandlyon.com/jeux-de-donnees/maquettes-3d-texturees-2018-communes-metropole-lyon/donnees
388
+
389
+ #### Phase 3: Optional Additional Data
390
+
391
+ - 3DBAG historical versions (API: https://api.3dbag.nl/)
392
+ - OSM POI History (Overpass API with date filters)
393
+
394
+ ### 7.2 Download Verification
395
+
396
+ - SHA256 hashes recorded for all downloaded files
397
+ - Building counts cross-referenced with published statistics
398
+ - Spatial extent and CRS validation
399
+ ## 8. Preprocessing Pipeline
400
+
401
+ ### 8.1 CityGML → CityJSON Conversion
402
+
403
+ ```
404
+ CityGML (.gml/.xml)
405
+ ↓ citygml-tools or custom parser
406
+ CityJSON (.json)
407
+ ↓ CRS unification → EPSG:7415 (or local UTM)
408
+ ↓ Centroid computation
409
+ ↓ Building-only filtering
410
+ ↓ Attribute standardization
411
+ ↓ Save as joblib/.pkl cache
412
+ ```
413
+
414
+ **Tools**:
415
+ - `citygml-tools` (Java CLI): `citygml-tools to-cityjson input.gml`
416
+ - `cityjson` Python package: for validation and manipulation
417
+ - Alternative: `cjio` Python package
418
+
419
+ ### 8.2 Ground-Truth Label Construction
420
+
421
+ ```
422
+ For each epoch pair (ti, tj):
423
+ ├── Load buildings from ti and tj
424
+ ├── Compute pairwise centroid distances
425
+ ├── Filter: distance < 2m → candidate matches
426
+ ├── Compute geometric consistency (area, volume ratios)
427
+ ├── Filter: ratio ∈ [0.7, 1.3] → probable matches
428
+ ├── Check CityGML ID persistence (if available)
429
+ ├── Assign confidence tier (high/medium/low)
430
+ ├── Manual sampling for verification (200 pairs)
431
+ └── Output: pairs CSV with [id_ti, id_tj, confidence, area_ratio, volume_ratio, distance]
432
+ ```
433
+
434
+ ### 8.3 Feature Extraction
435
+
436
+ For each building, extract 25 geometric properties (from 3dSAGER):
437
+ - **Size**: area, perimeter, volume, convex_hull_area, convex_hull_volume
438
+ - **Shape**: compactness_2d, compactness_3d, cubeness, hemisphericality, fractality
439
+ - **Dimensions**: bounding_box_width/length, aligned_bounding_box_width/length/height
440
+ - **Distribution**: density, elongation, shape_ind, axes_symmetry, num_vertices, circumference
441
+ - **Context**: ave_centroid_distance, height_diff, num_floors, perimeter_ind
442
+
443
+ **Temporal extension** (new for STEM):
444
+ - `delta_area`: |area_ti - area_tj| / area_ti
445
+ - `delta_volume`: |volume_ti - volume_tj| / volume_ti
446
+ - `delta_height`: |height_ti - height_tj| / height_ti
447
+ - `delta_compactness_3d`: same for compactness
448
+ - `time_gap_months`: temporal distance between epochs
449
+
450
+ ### 8.4 Disaster Simulation (for Task 3)
451
+
452
+ ```python
453
+ DisasterSimulator:
454
+ CRS Simulation:
455
+ - Random Z-axis rotation: θ ~ Uniform(0, 360°)
456
+ - Random translation: t ~ Uniform(-100km, +100km) in X, Y
457
+ - Applied to all candidate buildings
458
+
459
+ Damage Simulation:
460
+ - Per-building probability: P = 0.8
461
+ - Height reduction factor: f ~ Uniform(0.3, 0.95)
462
+ - Modified height = original_height × f
463
+ - Propagate to volume, convex_hull_volume, compactness_3d
464
+ ```
465
+
466
+ ---
467
+
468
+ ## 9. Experimental Protocol
469
+
470
+ ### 9.1 Baseline Experiment (Task 1: Cross-Source)
471
+
472
+ | Parameter | Value |
473
+ |---|---|
474
+ | Dataset | Hague (Source A vs Source B) |
475
+ | Features | 25 geometric properties |
476
+ | Feature operator | Division (F÷) |
477
+ | Blocking method | BKAFI |
478
+ | Classifier | XGBoost |
479
+ | Train:Val:Test | 60:20:20 |
480
+ | Evaluation | Precision, Recall, F1, Recall@k |
481
+ | Seeds | 5 |
482
+
483
+ ### 9.2 Cross-Time Experiment (Task 2)
484
+
485
+ | Parameter | Value |
486
+ |---|---|
487
+ | Dataset | Lyon (6 epoch pairs) |
488
+ | Train:Val:Test | 60:20:20 (per epoch pair) |
489
+ | Features | 25 geometric + 5 temporal delta |
490
+ | Classifier | XGBoost, GradientBoosting, RF, MLP |
491
+ | Evaluation mode | matching + blocking |
492
+ | Key analysis | F1 vs. time gap, property drift vs. time gap |
493
+
494
+ ### 9.3 Few-Shot Experiment
495
+
496
+ | Shots | Setting |
497
+ |---|---|
498
+ | K = 5 | 5 labeled pairs per epoch pair |
499
+ | K = 10 | 10 labeled pairs |
500
+ | K = 20 | 20 labeled pairs |
501
+ | K = 50 | 50 labeled pairs |
502
+ | K = 100 | 100 labeled pairs |
503
+
504
+ ### 9.4 Full ST-EM Experiment (Task 3)
505
+
506
+ | Parameter | Value |
507
+ |---|---|
508
+ | Base data | Lyon cross-time pairs |
509
+ | Simulation | CRS rotation + damage |
510
+ | Alignment | RANSAC rigid alignment |
511
+ | Re-scoring | α × geometric + (1-α) × spatial |
512
+ | Evaluation | Distance-based recall (10m, 25m, 50m) |
513
+
514
+ ### 9.5 Unsupervised/Zero-Shot Experiment
515
+
516
+ | Setting | Description |
517
+ |---|---|
518
+ | Cross-epoch transfer | Train on 2009→2012, test on 2015→2018 |
519
+ | Cross-city transfer | Train on Hague, test on Lyon (adapt features) |
520
+ | Property-ratio heuristic | F÷ operator + clustering, no labels |
521
+ ## 10. Delivery Checklist
522
+
523
+ ### 10.1 Phase 1: Infrastructure (Current)
524
+
525
+ - [x] 3dSAGER codebase cloned and analyzed
526
+ - [x] Python environment with all dependencies installed
527
+ - [x] HuggingFace repo initialized and configured
528
+ - [x] Specification document written (this file)
529
+
530
+ ### 10.2 Phase 2: Data Acquisition
531
+
532
+ - [x] Download 3dSAGER Hague dataset (Source A: 309MB, 36 CityJSON files; Source B: partial, 3 files)
533
+ - [ ] Complete Source B download (remaining CityJSON files)
534
+ - [ ] Download Lyon 2009-2015 from Zenodo (395 MB zip)
535
+ - [ ] Download Lyon 2018 from Grand Lyon portal
536
+ - [ ] Verify all downloads (counts, CRS, integrity)
537
+
538
+ ### 10.3 Phase 3: Preprocessing
539
+
540
+ - [ ] Convert Lyon CityGML → CityJSON
541
+ - [ ] Unify CRS across all epochs
542
+ - [ ] Extract building geometries and compute centroids
543
+ - [ ] Generate geometric properties per building
544
+ - [ ] Cache processed data as joblib files
545
+
546
+ ### 10.4 Phase 4: Benchmark Construction
547
+
548
+ - [ ] Construct ground-truth labels for all 6 Lyon epoch pairs
549
+ - [ ] Manual verification of random samples
550
+ - [ ] Generate train/val/test splits
551
+ - [ ] Compute dataset statistics
552
+ - [ ] Write dataset card (README.md for HuggingFace)
553
+
554
+ ### 10.5 Phase 5: Baseline Experiments
555
+
556
+ - [ ] Run 3dSAGER baseline on Hague dataset (reproduce paper results)
557
+ - [ ] Run cross-time matching on Lyon (supervised)
558
+ - [ ] Run few-shot experiments (K = 5, 10, 20, 50)
559
+ - [ ] Run disaster scenario (CRS + damage + alignment)
560
+ - [ ] Run unsupervised transfer experiments
561
+
562
+ ### 10.6 Phase 6: Upload & Documentation
563
+
564
+ - [ ] Upload all data to HuggingFace (eduzrh/STEM)
565
+ - [ ] Upload all code to HuggingFace
566
+ - [ ] Upload experiment results and logs
567
+ - [ ] Write paper-ready result tables and figures
568
+ - [ ] Push specification document
569
+
570
+ ### 10.7 Phase 7: Paper Writing
571
+
572
+ - [ ] Draft VLDBJ paper outline
573
+ - [ ] Write methodology section
574
+ - [ ] Generate all figures and tables
575
+ - [ ] Write experiments and results
576
+ - [ ] Polish and submit
577
+
578
+ ---
579
+
580
+ ## Appendix A: Risk Analysis
581
+
582
+ | Risk | Probability | Impact | Mitigation |
583
+ |---|---|---|---|
584
+ | Lyon data not downloadable | Low | High | Fall back to synthetic multi-epoch from 3DBAG versions |
585
+ | CityGML IDs not persistent | Medium | Medium | Use geometric + spatial heuristics for labeling |
586
+ | CityGML→CityJSON conversion fails | Low | Medium | Use `citygml-tools` Java tool as backup |
587
+ | HuggingFace storage limits | Low | Low | Use Git LFS for large files; tier upgrade if needed |
588
+ | Lyon building count too large | Medium | Medium | Use spatial subset (1–2 arrondissements) |
589
+ | Disk space insufficient for Lyon | Medium | High | Use GPU machine with SSD; process per-arrondissement |
590
+
591
+ ## Appendix B: Timeline
592
+
593
+ | Week | Milestone |
594
+ |---|---|
595
+ | Week 1 | Environment setup, data download, preprocessing |
596
+ | Week 2 | Benchmark construction, baseline experiments |
597
+ | Week 3 | Full experiments, result analysis |
598
+ | Week 4 | Paper writing, final uploads |
599
+
600
+ ## Appendix C: Lyon Zenodo Data Details
601
+
602
+ - **Zenodo Record**: https://zenodo.org/record/3611354
603
+ - **File**: `Lyon_2009-2012-2015_Splitted_Stripped.zip` (394.9 MB compressed, ~50.9 GB uncompressed)
604
+ - **MD5**: `74b4610a11d9ca37951f5de2b747794f`
605
+ - **Content**: CityGML LOD2 buildings for Lyon, split by arrondissement, across 3 epochs (2009, 2012, 2015)
606
+ - **Preprocessing**: Original data had structural issues resolved; texture coordinates removed
607
+ - **2018 data**: Separate download from Grand Lyon Open Data Portal
608
+
609
+ ## Appendix D: Hague Dataset Details
610
+
611
+ - **Google Drive Folder**: https://drive.google.com/drive/folders/11dC2jn9fajcn2W0LWKBCgyuBxabkz4WU
612
+ - **Structure**:
613
+ - `RawCitiesData/The Hague/Source A/` — CityJSON files covering all wijks (36 files, ~309 MB)
614
+ - `RawCitiesData/The Hague/Source B/` — CityJSON files (3+ files, ~21 MB so far)
615
+ - `dataset_partitions/` — Pre-computed train/val/test splits (3 seed files)
616
+ - **CRS**: EPSG:7415 (Amersfoort / RD New + NAP height)
617
+ - **Format**: CityJSON v1.0/v1.1
618
+ - **LOD**: Mixed LOD1/LOD2
experiments/results/FinalResults_Hague_allmodels_v1_Operator=division_Blocking=bkafi_matching_small_neg_samples=2_vector_normalization=True.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ,precision,recall,f1,training_time,inference_time
2
+ XGBClassifier,0.997,1.0,0.998,0.22,0.0
3
+ RandomForestClassifier,0.997,1.0,0.998,0.43,0.0
4
+ AdaBoostClassifier,0.991,1.0,0.995,1.43,0.02
5
+ MLPClassifier,0.958,0.979,0.968,4.92,0.0
experiments/results/Results_Hague_allmodels_v1_Operator=division_Blocking=bkafi.log ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INFO: dataset: Hague
2
+ INFO: seeds_num: 1
3
+ INFO: evaluation_mode: matching
4
+ INFO: blocking_method: bkafi
5
+ INFO: dataset_size_version: small
6
+ INFO: vector_normalization: True
7
+ INFO: sdr_factor: False
8
+ INFO: neg_samples_num: 2
9
+ INFO: bkafi_criterion: feature_importance
10
+ INFO:
11
+ INFO: ==============================================================================================
12
+ INFO:
13
+ INFO: Seed: 1
14
+ INFO: ------------------------------------------------------------------------------
15
+ INFO: Partition file missing — generating for seed 1...
16
+ INFO: Loading dataset_partition_dict from data/dataset_partitions/Hague_seed1.pkl
17
+ INFO: dataset_partition_dict was loaded successfully
18
+ INFO: Generating test object dict and train object dict
19
+ INFO: Loading preprocessed cache: data/object_dicts/Hague_raw.joblib
20
+ INFO: → 15545 cands, 15545 index buildings
21
+ INFO: [grid filter] 20 shared cells → 9596 cands, 9596 index buildings
22
+ INFO: Filtered to 1557 train pairs, 764 test pairs (available cands=9596, index=9596)
23
+ INFO: Saving test object dict
24
+ INFO: Saving train object dict to data/object_dicts/Hague/train_matching_small_neg_samples_num=2_seed_1.joblib
25
+ INFO: Saving test object dict to data/object_dicts/Hague/test_matching_negative_sampling_small_neg_samples_num=2_seed_1.joblib
26
+ INFO: _extract_pairs[train]: dropped 1446/3003 pairs with IDs not in object_dict (kept 1557)
27
+ INFO: Generating train property dictionary
28
+ INFO: Property dictionary generation time: 22.3
29
+
30
+ INFO: train_property_dict was saved successfully
31
+ INFO:
32
+ INFO: _extract_pairs[test]: dropped 895/1659 pairs with IDs not in object_dict (kept 764)
33
+ INFO: Generating test property dictionary
34
+ INFO: Property dictionary generation time: 11.16
35
+
36
+ INFO: test_property_dict was saved successfully
37
+ INFO:
38
+ INFO: Generating train feature vectors
39
+ INFO: Generating test feature vectors
40
+ INFO: dataset_dict was saved successfully
41
+ INFO:
42
+ INFO: Training for matching
43
+ INFO: Training model XGBClassifier...
44
+ INFO: Model XGBClassifier was trained successfully in 0.22 seconds
45
+ INFO: Model XGBClassifier was saved successfully (matching)
46
+ INFO:
47
+ INFO: Model XGBClassifier was evaluated successfully in 0.0 seconds
48
+ INFO: Training model RandomForestClassifier...
49
+ INFO: Model RandomForestClassifier was trained successfully in 0.43 seconds
50
+ INFO: Model RandomForestClassifier was saved successfully (matching)
51
+ INFO:
52
+ INFO: Model RandomForestClassifier was evaluated successfully in 0.0 seconds
53
+ INFO: Training model AdaBoostClassifier...
54
+ INFO: Model AdaBoostClassifier was trained successfully in 1.43 seconds
55
+ INFO: Model AdaBoostClassifier was saved successfully (matching)
56
+ INFO:
57
+ INFO: Model AdaBoostClassifier was evaluated successfully in 0.02 seconds
58
+ INFO: Training model MLPClassifier...
59
+ INFO: Model MLPClassifier was trained successfully in 4.92 seconds
60
+ INFO: Model MLPClassifier was saved successfully (matching)
61
+ INFO:
62
+ INFO: Model MLPClassifier was evaluated successfully in 0.0 seconds
63
+ INFO:
64
+ INFO: Results for model XGBClassifier:
65
+ INFO: Precision: 0.997
66
+ INFO: Recall: 1.0
67
+ INFO: F1 score: 0.998
68
+ INFO: ------------------------------------------------------------------------------
69
+ INFO:
70
+ INFO:
71
+ INFO: Results for model RandomForestClassifier:
72
+ INFO: Precision: 0.997
73
+ INFO: Recall: 1.0
74
+ INFO: F1 score: 0.998
75
+ INFO: ------------------------------------------------------------------------------
76
+ INFO:
77
+ INFO:
78
+ INFO: Results for model AdaBoostClassifier:
79
+ INFO: Precision: 0.991
80
+ INFO: Recall: 1.0
81
+ INFO: F1 score: 0.995
82
+ INFO: ------------------------------------------------------------------------------
83
+ INFO:
84
+ INFO:
85
+ INFO: Results for model MLPClassifier:
86
+ INFO: Precision: 0.958
87
+ INFO: Recall: 0.979
88
+ INFO: F1 score: 0.968
89
+ INFO: ------------------------------------------------------------------------------
90
+ INFO:
91
+ INFO: [_run_alignment] 764 test pairs | model=XGBClassifier | anchors with score>=0.8: 325
92
+ INFO: [RigidAligner] RANSAC refit on 325/325 inliers (threshold=10.0 m, iterations=1000)
93
+ INFO: [RigidAligner] RANSAC: 325 anchors | 325 inliers | inlier mean residual = 0.84 m (all-anchor mean = 0.84 m)
94
+ INFO: [RigidAligner] Ground-truth comparison: rotation error = 0.03°, translation error = 185.3 m
95
+ INFO: [RigidAligner] Score re-scaling: geometric mean=0.426 → final mean=0.414 (alpha=0.5)
96
+ INFO: [RigidAligner] Aligned CityJSON written: results/aligned_candidates_seed1.json (326 buildings, 2.3 MB)
97
+ INFO: [_run_alignment] Top-10 mean geometric score: 0.999 → final score: 0.999
98
+ INFO: [Metrics] Before alignment (score≥0.5) — Precision: 0.997 Recall: 1.0 F1: 0.998
99
+ INFO: [Metrics] After alignment (distance-based, n=326 matched buildings) — mean dist: 0.8 m | median dist: 0.7 m | max dist: 8.0 m
100
+ INFO: [Metrics] After alignment distance recall@10m: 1.0 (326/326 buildings within 10 m of true match)
101
+ INFO: [Metrics] After alignment distance recall@25m: 1.0 (326/326 buildings within 25 m of true match)
102
+ INFO: [Metrics] After alignment distance recall@50m: 1.0 (326/326 buildings within 50 m of true match)
103
+ INFO: Done!
experiments/results/aligned_candidates_seed1.json ADDED
The diff for this file is too large to render. See raw diff
 
experiments/run_experiments.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+
4
+ bkafi_criterion=("feature_importance")
5
+ dataset_sizes=("small")
6
+ normalizations=("True")
7
+ sdr_factors=("False")
8
+ eval_mode="matching"
9
+
10
+ for criterion in "${bkafi_criterion[@]}"; do
11
+ for size in "${dataset_sizes[@]}"; do
12
+ for normalization in "${normalizations[@]}"; do
13
+ for sdr in "${sdr_factors[@]}"; do
14
+ echo "=================================================================================================="
15
+ # if eval_mode == blocking print the following
16
+ if [[ $eval_mode == "blocking" ]]; then
17
+ echo "Running blocking with: bkafi_criterion=$criterion, size=$size, vector_normalization=$normalization, SDR=$sdr"
18
+ else
19
+ echo "Running matching with: bkafi_criterion=$criterion, size=$size, vector_normalization=$normalization, SDR=$sdr"
20
+ fi
21
+
22
+ python main.py \
23
+ --bkafi_criterion $criterion \
24
+ --evaluation_mode $eval_mode \
25
+ --dataset_size_version $size \
26
+ --vector_normalization $normalization \
27
+ --sdr_factor $sdr
28
+ done
29
+ done
30
+ done
31
+ done
experiments/run_full_pipeline.sh ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # run_full_pipeline.sh
4
+ # Full end-to-end 3dSAGER pipeline — run from scratch on a clean machine.
5
+ #
6
+ # Roles (after swap):
7
+ # cands = Source B (the set we try to match / may be damaged/rotated)
8
+ # index = Source A (the reference set)
9
+ #
10
+ # Usage:
11
+ # bash run_full_pipeline.sh [small|medium|large]
12
+ # Default dataset size: medium
13
+ #
14
+ # Requirements:
15
+ # - conda environment '3dsager' installed
16
+ # - CityJSON files present at paths in dataset_configs.json
17
+ # =============================================================================
18
+
19
+ set -e # exit immediately on any error
20
+
21
+ DATASET_SIZE=${1:-medium}
22
+ DATASET_NAME="Hague"
23
+ SEEDS=1
24
+ CONDA_ENV="3dsager"
25
+
26
+ echo "============================================================"
27
+ echo " 3dSAGER Full Pipeline"
28
+ echo " Dataset: ${DATASET_NAME} | Size: ${DATASET_SIZE} | Seeds: ${SEEDS}"
29
+ echo "============================================================"
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # 0. Clean stale caches so nothing from a previous run bleeds through
33
+ # ---------------------------------------------------------------------------
34
+ echo ""
35
+ echo "[0/4] Cleaning stale cache files..."
36
+
37
+ rm -f data/object_dicts/Hague_raw.joblib
38
+ rm -f data/object_dicts/Hague/*.joblib
39
+ rm -f data/property_dicts/Hague*.joblib
40
+ rm -f data/property_dicts/features.parquet
41
+ rm -f data/dataset_dicts/Hague*.joblib
42
+ rm -f data/dataset_partitions/Hague*.pkl
43
+ rm -rf results/demo_inference/
44
+
45
+ echo " Done."
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # 1. Preprocess raw CityJSON files → Hague_raw.joblib
49
+ # ---------------------------------------------------------------------------
50
+ echo ""
51
+ echo "[1/4] Preprocessing CityJSON files (preprocess_hague.py)..."
52
+
53
+ conda run -n ${CONDA_ENV} python preprocess_hague.py
54
+
55
+ echo " Done — Hague_raw.joblib created."
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # 2. Train all models + blocking + alignment
59
+ # ---------------------------------------------------------------------------
60
+ echo ""
61
+ echo "[2/4] Running main pipeline (train + block + test + align)..."
62
+
63
+ conda run -n ${CONDA_ENV} python main.py \
64
+ --dataset_name ${DATASET_NAME} \
65
+ --evaluation_mode matching \
66
+ --dataset_size_version ${DATASET_SIZE} \
67
+ --seeds_num ${SEEDS} \
68
+ --bkafi_criterion feature_importance \
69
+ --vector_normalization True \
70
+ --sdr_factor False
71
+
72
+ echo " Done — models saved, results CSV written."
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # 3. Generate demo files for all 6 models
76
+ # ---------------------------------------------------------------------------
77
+ echo ""
78
+ echo "[3/4] Generating demo inference files..."
79
+
80
+ for MODEL in XGBClassifier GradientBoostingClassifier BaggingClassifier \
81
+ RandomForestClassifier AdaBoostClassifier MLPClassifier; do
82
+ echo " → ${MODEL}"
83
+ conda run -n ${CONDA_ENV} python generate_demo_files.py \
84
+ --model ${MODEL} \
85
+ --seed 1
86
+ done
87
+
88
+ echo " Done — demo files written to results/demo_inference/"
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # 4. Summary
92
+ # ---------------------------------------------------------------------------
93
+ echo ""
94
+ echo "============================================================"
95
+ echo " Pipeline complete."
96
+ echo ""
97
+ echo " Results CSV: results/matching csv files/"
98
+ echo " Aligned JSON: results/aligned_candidates_seed1.json"
99
+ echo " Demo files: results/demo_inference/"
100
+ echo " Log: results/Results_${DATASET_NAME}_allmodels_v1_*.log"
101
+ echo "============================================================"