eduzrh commited on
Commit
d934656
·
verified ·
1 Parent(s): 9e0a6ef

Upload STER-GI code

Browse files
code/blocking.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import config
2
+ from utils import *
3
+ import faiss
4
+ import numpy as np
5
+ from collections import defaultdict
6
+ from time import time
7
+ from scipy.spatial import KDTree
8
+ import tqdm
9
+ from sklearn.preprocessing import RobustScaler
10
+
11
+
12
+ class Blocker:
13
+ def __init__(self, dataset_name, object_dict, property_dict, feature_importance_scores, property_ratios,
14
+ blocking_method, sdr_factor, bkafi_criterion, train_or_test):
15
+ self.dataset_name = dataset_name
16
+ self.blocking_method = blocking_method
17
+ self.nn_param = config.Blocking.nn_param
18
+ self.cand_pairs_per_item_list = config.Blocking.cand_pairs_per_item_list
19
+ self.bkafi_dim_list = config.Blocking.bkafi_dim_list
20
+ self.bkafi_criterion = bkafi_criterion
21
+ self.nbits = config.Blocking.nbits
22
+ self.object_dict = object_dict
23
+ self.property_dict = property_dict
24
+ self.feature_importance_scores = feature_importance_scores
25
+ self.property_ratios = property_ratios
26
+ self.sdr_factor = sdr_factor
27
+ self.train_or_test = train_or_test
28
+ self.centroids_dict = self._get_centroids()
29
+ self.cands_mapping = {ind: orig_ind for ind, orig_ind in enumerate(self.object_dict['cands'].keys())}
30
+ self.index_mapping = {ind: orig_ind for ind, orig_ind in enumerate(self.object_dict['index'].keys())}
31
+ self.blocking_method_dict = self._get_blocking_method_dict()
32
+ self.nn_dict, self.dist_dict, self.blocking_execution_time = self._run_blocking()
33
+ self.pos_pairs_dict, self.neg_pairs_dict = self._get_candidate_pairs()
34
+
35
+ def _get_centroids(self):
36
+ centroids_dict = defaultdict(dict)
37
+ for objects_type in ['cands', 'index']:
38
+ centroids_dict[objects_type] = {obj_ind: obj_data['centroid'] for obj_ind, obj_data in
39
+ self.object_dict[objects_type].items()}
40
+ centroids_dict[objects_type] = dict(sorted(centroids_dict[objects_type].items()))
41
+ return centroids_dict
42
+
43
+ @staticmethod
44
+ def _get_ind_mapping(centroids):
45
+ return {ind: orig_ind for ind, orig_ind in enumerate(sorted(centroids))}
46
+
47
+ def _get_blocking_method_dict(self):
48
+ blocking_method_dict = {'bkafi': self._run_bkafi,
49
+ 'ViT-B_32': self._run_vit,
50
+ 'ViT-L_14': self._run_vit,
51
+ 'centroid': self._run_exhaustive,
52
+ 'centroid_with_transform': self._run_exhaustive,
53
+ # 'lsh': self._run_lsh,
54
+ # 'kdtree': self._run_kdtree,
55
+ }
56
+ return blocking_method_dict
57
+
58
+ def _run_blocking(self):
59
+ nn_dict, dists_dict, blocking_execution_time = self.blocking_method_dict[self.blocking_method]()
60
+ return nn_dict, dists_dict, blocking_execution_time
61
+
62
+ def _run_exhaustive(self):
63
+ nn_dict, dists_dict = {}, {}
64
+ cands_centroids_np = np.array(list(self.centroids_dict['cands'].values()), dtype=np.float32)
65
+ index_centroids_np = np.array(list(self.centroids_dict['index'].values()), dtype=np.float32)
66
+ if self.blocking_method == 'centroid_with_transform':
67
+ cands_centroids_np = self._transform_centroids(cands_centroids_np, index_centroids_np)
68
+ index = faiss.IndexFlatL2(index_centroids_np.shape[1])
69
+ index.add(index_centroids_np)
70
+ start = time()
71
+ for i, query_centroid in enumerate(cands_centroids_np):
72
+ dists, neighbors = index.search(np.array([query_centroid]), self.nn_param)
73
+ nn_dict[self.cands_mapping[i]] = [self.index_mapping[ind] for ind in neighbors.flatten()]
74
+ dists_dict[self.cands_mapping[i]] = [dist for dist in dists.flatten()]
75
+ end = time()
76
+ return nn_dict, dists_dict, round(end - start, 3)
77
+
78
+ def _transform_centroids(self, cands_centroids_np, index_centroids_np):
79
+ index_mean = np.mean(index_centroids_np, axis=0)
80
+ cands_mean = np.mean(cands_centroids_np, axis=0)
81
+ index_centered = index_centroids_np - index_mean
82
+ cands_centered = cands_centroids_np - cands_mean
83
+ H = np.dot(index_centered, cands_centered.T)
84
+ U, S, Vt = np.linalg.svd(H)
85
+ rotation_matrix = np.dot(Vt.T, U.T)
86
+ if np.linalg.det(rotation_matrix) < 0:
87
+ Vt[-1, :] *= -1
88
+ rotation_matrix = np.dot(Vt.T, U.T)
89
+ translation_vector = cands_mean - np.dot(index_mean, rotation_matrix)
90
+ scaling_factor = np.linalg.norm(cands_centered) / np.linalg.norm(index_centered)
91
+ cands_centroids_np = scaling_factor * np.dot(index_centroids_np, rotation_matrix) + translation_vector
92
+ return cands_centroids_np
93
+
94
+ def _run_lsh(self):
95
+ nn_dict, dists_dict = {}, {}
96
+ cands_centroids_np = np.array(list(self.centroids_dict['cands'].values()), dtype=np.float32)
97
+ index_centroids_np = np.array(list(self.centroids_dict['index'].values()), dtype=np.float32)
98
+ index = faiss.IndexLSH(index_centroids_np.shape[1], self.nbits)
99
+ index.add(index_centroids_np)
100
+ for i, query_centroid in enumerate(cands_centroids_np):
101
+ dists, neighbors = index.search(np.array([query_centroid]), self.nn_param)
102
+ nn_dict[self.cands_mapping[i]] = [self.index_mapping[ind] for ind in neighbors.flatten()]
103
+ dists_dict[self.cands_mapping[i]] = [dist for dist in dists.flatten()]
104
+ return nn_dict, dists_dict
105
+
106
+ def _run_kdtree(self, search_dict):
107
+ robust_scaler = RobustScaler()
108
+ nn_dict, dists_dict = {}, {}
109
+ cands_vectors_np = np.array(list(search_dict['cands'].values()), dtype=np.float32)
110
+ index_vectors_np = np.array(list(search_dict['index'].values()), dtype=np.float32)
111
+ cands_vectors_np = robust_scaler.fit_transform(cands_vectors_np)
112
+ index_vectors_np = robust_scaler.transform(index_vectors_np)
113
+ index = KDTree(index_vectors_np)
114
+ dists, neighbors = index.query(cands_vectors_np, self.nn_param)
115
+ for i, query_centroid in enumerate(cands_vectors_np):
116
+ nn_dict[self.cands_mapping[i]] = [self.index_mapping[ind] for ind in neighbors[i]]
117
+ dists_dict[self.cands_mapping[i]] = [round(dist, 3) for dist in dists[i]]
118
+ return nn_dict, dists_dict
119
+
120
+ def _run_bkafi(self):
121
+ if self.train_or_test == 'train':
122
+ return self._run_bkafi_train()
123
+ nn_dict, dists_dict = {}, {}
124
+ model_name = config.Models.blocking_model
125
+ execution_time_dict = {}
126
+ for bkafi_dim in self.bkafi_dim_list:
127
+ target_blocking_features = self._get_target_blocking_features(model_name, bkafi_dim)
128
+ bkafi_dict = self._get_bkafi_dict(target_blocking_features)
129
+ start_time = time()
130
+ nn_dict[bkafi_dim], dists_dict[bkafi_dim] = self._run_kdtree(bkafi_dict)
131
+ end_time = time()
132
+ execution_time_dict[bkafi_dim] = round(end_time - start_time, 3)
133
+ return nn_dict, dists_dict, execution_time_dict
134
+
135
+ def _get_target_blocking_features(self, model_name, bkafi_dim):
136
+ if self.bkafi_criterion == 'std':
137
+ target_blocking_features = {prop: prop_information for prop, prop_information in
138
+ list(self.property_ratios.items())[:bkafi_dim]}
139
+ else: # feature_importance
140
+ target_blocking_features = {feature: self.property_ratios[feature.split('_ratio')[0]]
141
+ for feature, _ in self.feature_importance_scores[model_name][:bkafi_dim]}
142
+ return target_blocking_features
143
+
144
+ def _run_bkafi_train(self):
145
+ nn_dict, dists_dict = {}, {}
146
+ model_name = config.Models.blocking_model
147
+ bkafi_dim = len(self.feature_importance_scores[model_name])
148
+ target_blocking_features = {feature: self.property_ratios[feature.split('_ratio')[0]]
149
+ for feature, _ in self.feature_importance_scores[model_name][:bkafi_dim]}
150
+ bkafi_dict = self._get_bkafi_dict(target_blocking_features)
151
+ nn_dict[bkafi_dim], dists_dict[bkafi_dim] = self._run_kdtree(bkafi_dict)
152
+ return nn_dict, dists_dict, None
153
+
154
+ def _get_bkafi_dict(self, target_blocking_features):
155
+ bkafi_dict = defaultdict(dict)
156
+ factor_dict = self._get_bkafi_factor_dict(target_blocking_features)
157
+ for obj_type in ['cands', 'index']:
158
+ for obj_ind in self.object_dict[obj_type].keys():
159
+ bkafi_dict[obj_type][obj_ind] = []
160
+ for feature in target_blocking_features:
161
+ property_val = self.property_dict[feature.split('_ratio')[0]][obj_type][obj_ind]
162
+ bkafi_dict[obj_type][obj_ind].append(property_val * factor_dict[obj_type][feature])
163
+ bkafi_dict[obj_type][obj_ind] = np.array(bkafi_dict[obj_type][obj_ind])
164
+ return bkafi_dict
165
+
166
+ def _get_bkafi_factor_dict(self, target_blocking_features):
167
+ factor_dict = defaultdict(dict)
168
+ if self.sdr_factor:
169
+ factor_dict['cands'] = {feature: target_blocking_features[feature]['mean']
170
+ for feature in target_blocking_features}
171
+ else:
172
+ factor_dict['cands'] = {feature: 1.0 for feature in target_blocking_features}
173
+ factor_dict['index'] = {feature: 1.0 for feature in target_blocking_features}
174
+ return factor_dict
175
+
176
+ def _run_vit(self):
177
+ vit_model_name = self.blocking_method
178
+ embeddings_dict = get_embeddings_wrapper(self.dataset_name, self.object_dict, vit_model_name)
179
+ faiss_embds_dict, mapping_dict = get_faiss_embeddings(embeddings_dict)
180
+ dim = faiss_embds_dict['index'].shape[1]
181
+ index = faiss.IndexFlatIP(dim)
182
+ index.add(faiss_embds_dict['index'])
183
+ nn_dict, dists_dict = {}, {}
184
+ start_time = time()
185
+ for i, cand_query in enumerate(faiss_embds_dict['cands']):
186
+ query = cand_query.reshape(1, -1)
187
+ dists, neighbors = index.search(query, self.nn_param)
188
+ nn_dict[mapping_dict['cands'][i]] = [mapping_dict['index'][ind] for ind in neighbors[0]]
189
+ dists_dict[mapping_dict['cands'][i]] = [dist for dist in dists[0]]
190
+ end_time = time()
191
+ return nn_dict, dists_dict, round(end_time - start_time, 3)
192
+
193
+
194
+ @staticmethod
195
+ def _get_start_ind4nn(nn_inds, cand_ind):
196
+ if nn_inds[0] + 1 == cand_ind:
197
+ return 1
198
+ else:
199
+ return 0
200
+
201
+ def _get_candidate_pairs(self):
202
+ if self.train_or_test == 'train':
203
+ cand_pairs_per_item_list = [self.cand_pairs_per_item_list[0]]
204
+ else:
205
+ cand_pairs_per_item_list = self.cand_pairs_per_item_list
206
+ if 'bkafi' in self.blocking_method:
207
+ return self._get_candidate_pairs_bkafi(cand_pairs_per_item_list)
208
+ else:
209
+ return self._get_candidate_pairs_not_bkafi(cand_pairs_per_item_list)
210
+
211
+ def _get_candidate_pairs_bkafi(self, cand_pairs_per_item_list):
212
+ pos_pairs_dict, neg_pairs_dict = defaultdict(dict), defaultdict(dict)
213
+ for bkafi_dim in self.nn_dict.keys():
214
+ for list_ind, cand_pairs_per_item in enumerate(cand_pairs_per_item_list):
215
+ if list_ind == 0:
216
+ pos_pairs_dict[bkafi_dim][cand_pairs_per_item] = []
217
+ neg_pairs_dict[bkafi_dim][cand_pairs_per_item] = []
218
+ else:
219
+ previous_val = self.cand_pairs_per_item_list[list_ind - 1]
220
+ pos_pairs_dict[bkafi_dim][cand_pairs_per_item] = pos_pairs_dict[bkafi_dim][previous_val].copy()
221
+ neg_pairs_dict[bkafi_dim][cand_pairs_per_item] = neg_pairs_dict[bkafi_dim][previous_val].copy()
222
+ for cand_ind, nn_inds in self.nn_dict[bkafi_dim].items():
223
+ start_ind = self.cand_pairs_per_item_list[list_ind - 1] if list_ind > 0 else 0
224
+ # cand_ind = str(cand_ind)
225
+ for nn_ind in nn_inds[start_ind:cand_pairs_per_item]:
226
+ if cand_ind == nn_ind:
227
+ pos_pairs_dict[bkafi_dim][cand_pairs_per_item].append((cand_ind, nn_ind))
228
+ else:
229
+ neg_pairs_dict[bkafi_dim][cand_pairs_per_item].append((cand_ind, nn_ind))
230
+ return pos_pairs_dict, neg_pairs_dict
231
+
232
+
233
+ def _get_candidate_pairs_not_bkafi(self, cand_pairs_per_item_list):
234
+ pos_pairs_dict, neg_pairs_dict = dict(), dict()
235
+ for list_ind, cand_pairs_per_item in enumerate(cand_pairs_per_item_list):
236
+ if list_ind == 0:
237
+ pos_pairs_dict[cand_pairs_per_item] = []
238
+ neg_pairs_dict[cand_pairs_per_item] = []
239
+ else:
240
+ previous_val = self.cand_pairs_per_item_list[list_ind - 1]
241
+ pos_pairs_dict[cand_pairs_per_item] = pos_pairs_dict[previous_val].copy()
242
+ neg_pairs_dict[cand_pairs_per_item] = neg_pairs_dict[previous_val].copy()
243
+ for cand_ind, nn_inds in self.nn_dict.items():
244
+ start_ind = self.cand_pairs_per_item_list[list_ind - 1] if list_ind > 0 else 0
245
+ cand_ind = str(cand_ind)
246
+ for nn_ind in nn_inds[start_ind:cand_pairs_per_item]:
247
+ if cand_ind == nn_ind:
248
+ pos_pairs_dict[cand_pairs_per_item].append((cand_ind, nn_ind))
249
+ else:
250
+ neg_pairs_dict[cand_pairs_per_item].append((cand_ind, nn_ind))
251
+ return pos_pairs_dict, neg_pairs_dict
252
+
253
+ def _get_local_mapping_dict(self):
254
+ """
255
+ This function returns the mapping dictionary of the objects in the current object_dict.
256
+ The mapping is required because in some datasets object file names are recognized as integers and in some
257
+ datasets as uids
258
+ """
259
+ local_mapping_dict = defaultdict(dict)
260
+ if 'mapping_dict' not in self.object_dict.keys():
261
+ local_mapping_dict['cands'] = {ind: ind for ind in self.object_dict['cands'].keys()}
262
+ local_mapping_dict['index'] = {ind: ind for ind in self.object_dict['index'].keys()}
263
+ else:
264
+ local_mapping_dict['cands'] = self.object_dict['mapping_dict']['cands']
265
+ local_mapping_dict['index'] = self.object_dict['mapping_dict']['index']
266
+ return local_mapping_dict
267
+
code/classifier.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.model_selection import GridSearchCV
2
+ from sklearn.ensemble import (RandomForestClassifier, AdaBoostClassifier,
3
+ GradientBoostingClassifier, BaggingClassifier)
4
+ from xgboost import XGBClassifier
5
+ from sklearn.svm import SVC
6
+ from sklearn.linear_model import LogisticRegression
7
+ from sklearn.metrics import precision_score, recall_score, f1_score, make_scorer
8
+ import logging
9
+ from sklearn.neural_network import MLPClassifier
10
+ import joblib
11
+ from collections import defaultdict
12
+ import config
13
+ import os
14
+ from sklearn.preprocessing import LabelEncoder
15
+ import numpy as np
16
+ from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
17
+ import matplotlib.pyplot as plt
18
+ from utils import get_feature_name_list, get_file_name
19
+ from time import time
20
+
21
+
22
+ class FlexibleClassifier:
23
+ def __init__(self, dataset_dict, property_dict, params_dict, seed, logger, dataset_name, evaluation_mode,
24
+ dataset_size_version, neg_samples_num, load_trained_models=False, cv=5, dirty=False,
25
+ contamination_level=0.0, contaminated_indices_dict=None):
26
+ self.dataset_dict = dataset_dict
27
+ self.property_dict = property_dict
28
+ self.params_dict = params_dict
29
+ self.seed = seed
30
+ self.dataset_size_version = dataset_size_version
31
+ self.neg_samples_num = neg_samples_num
32
+ self.load_trained_models = load_trained_models
33
+ self.dirty = dirty
34
+ self.cv = cv
35
+ self.models_path = f"{config.FilePaths.saved_models_path}/{dataset_name}/"
36
+ self.dataset_name = dataset_name
37
+ self.logger = logger
38
+ self.evaluation_mode = evaluation_mode
39
+ self.contamination_level = contamination_level
40
+ self.contaminated_indices_dict = contaminated_indices_dict
41
+ self.model_dict = self._get_model_dict()
42
+ self.file_name = get_file_name()
43
+ self.scorer = make_scorer(f1_score, average='macro')
44
+ self.best_model_dict, self.result_dict = self._train_and_evaluate_all_models()
45
+ self._print_results()
46
+
47
+ def _get_model_dict(self):
48
+ model_dict = {
49
+ 'RandomForestClassifier': RandomForestClassifier(random_state=self.seed),
50
+ 'SVC': SVC(random_state=self.seed),
51
+ 'LogisticRegression': LogisticRegression(random_state=self.seed),
52
+ 'MLPClassifier': MLPClassifier(random_state=self.seed),
53
+ 'AdaBoostClassifier': AdaBoostClassifier(random_state=self.seed),
54
+ 'GradientBoostingClassifier': GradientBoostingClassifier(random_state=self.seed),
55
+ 'BaggingClassifier': BaggingClassifier(random_state=self.seed),
56
+ 'XGBClassifier': XGBClassifier(random_state=self.seed)
57
+ }
58
+ return model_dict
59
+
60
+ def _get_model_general_file_name(self):
61
+ general_file_name = (f"{self.evaluation_mode}_{self.file_name}_{self.dataset_size_version}_"
62
+ f"neg_samples_num={self.neg_samples_num}")
63
+ if self.contamination_level > 0.0:
64
+ general_file_name += f"_contamination_level={self.contamination_level}"
65
+ return general_file_name
66
+
67
+ def _save_model(self, model, model_name):
68
+ general_file_name = self._get_model_general_file_name()
69
+ if not os.path.exists(self.models_path[:-1]):
70
+ os.makedirs(self.models_path[:-1])
71
+ try:
72
+ model_file_name = f'{self.models_path}{model_name}_{general_file_name}_seed{self.seed}.joblib'
73
+ feature_name_list = self._get_final_feature_name_list()
74
+ joblib.dump({'model': model, 'feature_name_list': feature_name_list}, model_file_name)
75
+ logging.info(f"Model {model_name} was saved successfully ({self.evaluation_mode})")
76
+ logging.info('')
77
+ except Exception as e:
78
+ logging.error(f"Error happened while saving model {model_name} ({self.evaluation_mode}): {e}")
79
+
80
+ def _load_model(self, model_name):
81
+ general_file_name = self._get_model_general_file_name()
82
+ try:
83
+ model = joblib.load(f'{self.models_path}{model_name}_{general_file_name}_seed{self.seed}.joblib')
84
+ logging.info(f"Model {model_name} was loaded successfully")
85
+ logging.info('')
86
+ print(f"Model {model_name} was loaded successfully {self.evaluation_mode})")
87
+ return model['model']
88
+ except Exception as e:
89
+ logging.error(f"Error happened while loading model {model_name}: {e}. Starting training...")
90
+ print(f"Error happened while loading model {model_name}: {e}. Starting training...")
91
+ return None
92
+
93
+ @staticmethod
94
+ def _get_final_feature_name_list():
95
+ operator = config.Features.operator
96
+ feature_name_list = get_feature_name_list(operator)
97
+ return feature_name_list
98
+
99
+ @staticmethod
100
+ def _get_neighborhood_feature_name_list():
101
+ if config.Features.knn_buildings == 0:
102
+ return []
103
+ with_knn = [f"{i}_nearest_building_dists" for i in range(1, config.Features.knn_buildings + 1)]
104
+ other_features = [feature for feature in config.Features.neighborhood if feature != "nearest_building_dists"]
105
+ return with_knn + other_features
106
+
107
+ @staticmethod
108
+ def _get_roads_feature_name_list():
109
+ if config.Features.knn_roads == 0:
110
+ return []
111
+ with_knn = [f"{i}_nearest_road_dists" for i in range(1, config.Features.knn_roads + 1)]
112
+ other_features = [feature for feature in config.Features.roads if feature != "nearest_road_dists"]
113
+ return with_knn + other_features
114
+
115
+ def _train_and_evaluate_all_models(self):
116
+ result_dict = defaultdict(dict)
117
+ best_model_dict = defaultdict(dict)
118
+ for model_name, model_params in self.params_dict.items():
119
+ try:
120
+ best_model_dict, result_dict = self._train_and_evaluate_model_wrapper(result_dict, best_model_dict,
121
+ model_name, model_params)
122
+ except Exception as e:
123
+ logging.error(f"Error for model {model_name}: {e}")
124
+ return best_model_dict, result_dict
125
+
126
+ def _train_and_evaluate_model_wrapper(self, result_dict, best_model_dict, model_name, model_params):
127
+ if self.contaminated_indices_dict is not None:
128
+ best_model_dict[model_name], result_dict = self._train_and_evaluate_model_contam(result_dict,
129
+ model_name,
130
+ model_params)
131
+ elif self.dirty is True:
132
+ best_model_dict[model_name], result_dict = self._train_and_evaluate_model_dirty(result_dict,
133
+ model_name,
134
+ model_params)
135
+
136
+ else:
137
+ best_model_dict[model_name], result_dict = self._train_and_evaluate_model(result_dict,
138
+ model_name,
139
+ model_params)
140
+ return best_model_dict, result_dict
141
+
142
+ def _get_best_model(self, model_name, params):
143
+ if self.load_trained_models:
144
+ best_model = self._load_model(model_name)
145
+ if best_model is not None:
146
+ return best_model, 0.0
147
+ model = self.model_dict[model_name]
148
+ best_model, training_time = self._train_model(model_name, model, params)
149
+ self._save_model(best_model, model_name)
150
+ return best_model, training_time
151
+
152
+ def _train_and_evaluate_model(self, result_dict, model_name, params):
153
+ best_model, training_time = self._get_best_model(model_name, params)
154
+ feature_name_list = self._get_final_feature_name_list()
155
+ data_type = 'train' if self.evaluation_mode == "blocking" else 'test'
156
+ x_test = self.dataset_dict[data_type]['X']
157
+ start_time = time()
158
+ y_test_preds = best_model.predict(x_test)
159
+ inference_time = round(time() - start_time, 2)
160
+ self.logger.info(f"Model {model_name} was evaluated successfully in {inference_time} seconds")
161
+ result_dict = self._insert_results_to_dict(result_dict, model_name, y_test_preds,
162
+ training_time, inference_time)
163
+ return {'model': best_model, 'feature_name_list': feature_name_list}, result_dict
164
+
165
+ def _train_and_evaluate_model_contam(self, result_dict, model_name, params):
166
+ best_model, _ = self._get_best_model(model_name, params)
167
+ feature_name_list = self._get_final_feature_name_list()
168
+ contaminated_indices = self.contaminated_indices_dict['test']
169
+ x_test_all = self.dataset_dict['test']['X']
170
+ x_test_contaminated = x_test_all[contaminated_indices]
171
+ y_test_preds_all = best_model.predict(x_test_all)
172
+ y_test_preds_contaminated = best_model.predict(x_test_contaminated)
173
+ self.logger.info(f"Model {model_name} was evaluated successfully")
174
+ result_dict = self._insert_results_to_dict_contaminated(result_dict, model_name, y_test_preds_all,
175
+ y_test_preds_contaminated, contaminated_indices)
176
+ return {'model': best_model, 'feature_name_list': feature_name_list}, result_dict
177
+
178
+ def _train_and_evaluate_model_dirty(self, result_dict, model_name, params):
179
+ best_model, training_time = self._get_best_model(model_name, params)
180
+ feature_name_list = self._get_final_feature_name_list()
181
+ x_test = self.dataset_dict['test']['X']
182
+ x_test_dirty = self.dataset_dict['test_dirty']['X']
183
+ y_test_preds = best_model.predict(x_test)
184
+ y_test_preds_dirty = best_model.predict(x_test_dirty)
185
+ result_dict = self._insert_results_to_dict_dirty(result_dict, model_name, y_test_preds, y_test_preds_dirty)
186
+ return {'model': best_model, 'feature_name_list': feature_name_list}, result_dict
187
+
188
+ def _get_y_train(self, model_name):
189
+ y_train = self.dataset_dict['train']['Y']
190
+ if model_name == 'XGBClassifier':
191
+ le = LabelEncoder()
192
+ return le.fit_transform(y_train)
193
+ else:
194
+ return y_train
195
+
196
+ def _train_model(self, model_name, model, params):
197
+ start_time = time()
198
+ if 'train' not in self.dataset_dict.keys():
199
+ raise ValueError("You first need to run the code with "
200
+ "config.TrainingPhase.run_preparatory_phase = True")
201
+ x_train = self.dataset_dict['train']['X']
202
+ y_train = self._get_y_train(model_name)
203
+ self.logger.info(f"Training model {model.__class__.__name__}...")
204
+ grid_search = GridSearchCV(model, params, cv=self.cv, scoring=self.scorer)
205
+ grid_search.fit(x_train, y_train)
206
+ best_model = grid_search.best_estimator_
207
+ total_time = round(time() - start_time, 2)
208
+ self.logger.info(f"Model {model_name} was trained successfully in {total_time} seconds")
209
+ return best_model, total_time
210
+
211
+ def _insert_results_to_dict(self, result_dict, model_name, y_test_preds, training_time,
212
+ inference_time, y_prediction_file=None):
213
+ data_type = 'train' if self.evaluation_mode == "blocking" else 'test'
214
+ y_test = self.dataset_dict[data_type]['Y']
215
+ result_dict[model_name]['precision'] = precision_score(y_test, y_test_preds, average='binary')
216
+ result_dict[model_name]['recall'] = recall_score(y_test, y_test_preds, average='binary')
217
+ result_dict[model_name]['f1'] = f1_score(y_test, y_test_preds, average='binary')
218
+ result_dict[model_name]['training_time'] = training_time
219
+ result_dict[model_name]['inference_time'] = inference_time
220
+ return result_dict
221
+
222
+ def _insert_results_to_dict_contaminated(self, result_dict, model_name, y_test_preds_all,
223
+ y_test_preds_contaminated, contaminated_indices):
224
+ y_test_all = self.dataset_dict['test']['Y']
225
+ y_test_contaminated = y_test_all[contaminated_indices]
226
+ result_dict[model_name]['precision'] = precision_score(y_test_all, y_test_preds_all, average='binary')
227
+ result_dict[model_name]['recall'] = recall_score(y_test_all, y_test_preds_all, average='binary')
228
+ result_dict[model_name]['f1'] = f1_score(y_test_all, y_test_preds_all, average='binary')
229
+ result_dict[model_name]['precision_contaminated'] = precision_score(y_test_contaminated,
230
+ y_test_preds_contaminated,
231
+ average='binary')
232
+ result_dict[model_name]['recall_contaminated'] = recall_score(y_test_contaminated,
233
+ y_test_preds_contaminated,
234
+ average='binary')
235
+ result_dict[model_name]['f1_contaminated'] = f1_score(y_test_contaminated, y_test_preds_contaminated,
236
+ average='binary')
237
+ return result_dict
238
+
239
+ def _insert_results_to_dict_dirty(self, result_dict, model_name, y_test_preds, y_test_preds_dirty):
240
+ y_test = self.dataset_dict['test']['Y']
241
+ y_test_dirty = self.dataset_dict['test_dirty']['Y']
242
+ result_dict[model_name]['precision'] = precision_score(y_test, y_test_preds, average='binary')
243
+ result_dict[model_name]['recall'] = recall_score(y_test, y_test_preds, average='binary')
244
+ result_dict[model_name]['f1'] = f1_score(y_test, y_test_preds, average='binary')
245
+ result_dict[model_name]['precision_dirty'] = precision_score(y_test_dirty, y_test_preds_dirty,
246
+ average='binary')
247
+ result_dict[model_name]['recall_dirty'] = recall_score(y_test_dirty, y_test_preds_dirty,
248
+ average='binary')
249
+ result_dict[model_name]['f1_dirty'] = f1_score(y_test_dirty, y_test_preds_dirty, average='binary')
250
+ return result_dict
251
+
252
+ def _print_results(self):
253
+ for model_name, model_results in self.result_dict.items():
254
+ eval_mode_message = f" {self.evaluation_mode} mode (results over train set)" if (
255
+ self.evaluation_mode == "blocking") else ""
256
+ self.logger.info(f"{eval_mode_message}")
257
+ self.logger.info(f"Results for model {model_name}:")
258
+ self.logger.info(f"Precision: {round(model_results['precision'], 3)}")
259
+ self.logger.info(f"Recall: {round(model_results['recall'], 3)}")
260
+ self.logger.info(f"F1 score: {round(model_results['f1'], 3)}")
261
+ if self.contaminated_indices_dict is not None:
262
+ self.print_results_contaminated(model_results)
263
+ self.logger.info(3*'--------------------------')
264
+ self.logger.info('')
265
+ return
266
+
267
+ def print_results_contaminated(self, model_results):
268
+ self.logger.info(f"Contamination level: {self.contamination_level}")
269
+ self.logger.info(f"Precision (contaminated): {round(model_results['precision_contaminated'], 3)}")
270
+ self.logger.info(f"Recall (contaminated): {round(model_results['recall_contaminated'], 3)}")
271
+ self.logger.info(f"F1 score (contaminated): {round(model_results['f1_contaminated'], 3)}")
272
+ return
273
+
274
+ def feature_importance_extraction(self):
275
+ """
276
+ Extracts the feature importance scores for the best model (used in the preparatory phase for blocking)
277
+ """
278
+ feature_importance_dict = dict()
279
+ self.logger.info("Feature importance scores:\n")
280
+ for model_name in self.best_model_dict.keys():
281
+ best_model = self.best_model_dict[model_name]['model']
282
+ feature_name_list = self.best_model_dict[model_name]['feature_name_list']
283
+ sorted_importance_scores = sorted(zip(feature_name_list, best_model.feature_importances_),
284
+ key=lambda x: x[1], reverse=True)
285
+ self._print_feature_importance_scores(sorted_importance_scores)
286
+ feature_importance_dict[model_name] = sorted_importance_scores
287
+ self._save_feature_importance_scores(feature_importance_dict)
288
+ self.logger.info(3 * '*******************************************')
289
+ self.logger.info(3 * '*******************************************')
290
+ return feature_importance_dict
291
+
292
+ def _save_feature_importance_scores(self, sorted_importance_scores):
293
+ general_file_name = ''.join((self.file_name, '_feature_importance_dict'))
294
+ feature_importance_file_name = f'{self.models_path}_{general_file_name}_seed={self.seed}.joblib'
295
+ joblib.dump(sorted_importance_scores, feature_importance_file_name)
296
+ self.logger.info(f"Feature importance scores were saved successfully")
297
+ self.logger.info('')
298
+ return
299
+
300
+ def _print_feature_importance_scores(self, sorted_importance_scores):
301
+ for feature, score in sorted_importance_scores:
302
+ self.logger.info(f"{feature}: {round(score, 3)}")
303
+ self.logger.info(3 * '==============================')
304
+ self.logger.info('')
305
+ return
306
+
307
+ def get_property_ratios(self):
308
+ property_ratios = dict()
309
+ for prop, curr_prop_dict in self.property_dict.items():
310
+ ratio_hist = [curr_prop_dict['index'][ind] / curr_prop_dict['cands'][ind] for ind in
311
+ curr_prop_dict['index'].keys() if ind in curr_prop_dict['cands'].keys()]
312
+ property_ratios[prop] = {'mean': round(np.mean(ratio_hist), 3),
313
+ 'std': round(np.std(ratio_hist), 3)}
314
+ property_ratios = dict(sorted(property_ratios.items(), key=lambda item: item[1]['std']))
315
+ self._save_property_ratios(property_ratios)
316
+ return property_ratios
317
+
318
+ def _save_property_ratios(self, property_ratios):
319
+ general_file_name = ''.join((self.file_name, '_property_ratios'))
320
+ property_ratios_file_name = f'{self.models_path}{general_file_name}_seed={self.seed}.joblib'
321
+ joblib.dump(property_ratios, property_ratios_file_name)
322
+ self.logger.info(f"Matching pairs property ratios were saved successfully")
323
+ self.logger.info('')
324
+ return
code/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 = 50 # 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/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/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/ster_gi_idea3.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ STER-GI Idea 3: Denoise-to-Sibling (去噪造兄弟)
3
+ ================================================
4
+ - Train unconditional diffusion on ALL building property vectors (no labels)
5
+ - Generate "sibling" buildings via SDEdit (partial noise + denoise)
6
+ - Contrastive learning on (original, sibling) pairs
7
+ - Zero-shot evaluation on test pairs: encode → cosine sim → threshold → match
8
+
9
+ Baselines:
10
+ - real-only (raw property cosine): no training at all
11
+ - Idea 3 (denoise-to-sibling): diffusion + contrastive
12
+ """
13
+
14
+ import os, sys, time, warnings, argparse
15
+ import numpy as np
16
+ import joblib, pickle as pkl
17
+ import torch, torch.nn as nn, torch.nn.functional as F
18
+ from torch.utils.data import DataLoader, TensorDataset
19
+ from sklearn.preprocessing import StandardScaler
20
+ from sklearn.metrics import precision_score, recall_score, f1_score, average_precision_score
21
+ from collections import defaultdict
22
+
23
+ warnings.filterwarnings("ignore")
24
+
25
+ # ============================================================
26
+ # Config
27
+ # ============================================================
28
+ PROPERTY_NAMES = [
29
+ "bounding_box_width", "bounding_box_length", "area", "perimeter",
30
+ "perimeter_ind", "volume", "convex_hull_area", "convex_hull_volume",
31
+ "ave_centroid_distance", "height_diff", "num_floors", "axes_symmetry",
32
+ "compactness_2d", "compactness_3d", "density", "elongation",
33
+ "shape_ind", "hemisphericality", "fractality", "cubeness",
34
+ "circumference", "aligned_bounding_box_width", "aligned_bounding_box_length",
35
+ "aligned_bounding_box_height", "num_vertices"
36
+ ]
37
+
38
+ CFG = {
39
+ 'diffusion_steps': 1000,
40
+ 'diffusion_hidden': 256,
41
+ 'diffusion_layers': 4,
42
+ 'diffusion_epochs': 500,
43
+ 'diffusion_lr': 1e-3,
44
+ 'diffusion_batch_size': 512,
45
+ # SDEdit: how much noise to add (0=none, 1000=full)
46
+ 'sdedit_t0': 200,
47
+ 'num_siblings': 3,
48
+ # Encoder
49
+ 'encoder_hidden': 128,
50
+ 'encoder_dim': 64,
51
+ 'contrastive_epochs': 200,
52
+ 'contrastive_lr': 1e-3,
53
+ 'contrastive_temp': 0.07,
54
+ 'contrastive_batch': 1024,
55
+ # Eval: threshold sweep
56
+ 'eval_thresholds': [0.5, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.92, 0.95, 0.97, 0.99],
57
+ 'device': 'cuda' if torch.cuda.is_available() else 'cpu',
58
+ }
59
+
60
+ # ============================================================
61
+ # Data: Extract property vectors
62
+ # ============================================================
63
+ def extract_vectors(prop_dict, source, id_list=None):
64
+ """Extract property matrix for given source ('cands'/'index') and optional id filter"""
65
+ first_prop = PROPERTY_NAMES[0]
66
+ all_ids = list(prop_dict[first_prop][source].keys()) if id_list is None else id_list
67
+ X = np.zeros((len(all_ids), len(PROPERTY_NAMES)), dtype=np.float32)
68
+ valid_ids = []
69
+ for i, bid in enumerate(all_ids):
70
+ vec = []
71
+ ok = True
72
+ for pname in PROPERTY_NAMES:
73
+ val = prop_dict[pname][source].get(bid, None)
74
+ if val is None or (isinstance(val, float) and np.isnan(val)):
75
+ val = 0.0
76
+ vec.append(float(val))
77
+ X[i] = vec
78
+ valid_ids.append(bid)
79
+ return X, valid_ids
80
+
81
+
82
+ def load_all_train_vectors(seed):
83
+ """Load property vectors for ALL training buildings (both cands and index)"""
84
+ train_path = (f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_"
85
+ f"neg_samples_num=2_vector_normalization=True_seed={seed}.joblib")
86
+ prop = joblib.load(train_path)
87
+
88
+ X_cands, ids_cands = extract_vectors(prop, 'cands')
89
+ X_index, ids_index = extract_vectors(prop, 'index')
90
+ X = np.concatenate([X_cands, X_index], axis=0)
91
+ all_ids = ids_cands + ids_index
92
+ print(f"Loaded {len(X)} train building vectors ({len(X_cands)} cands + {len(X_index)} index)")
93
+ return X, all_ids, prop
94
+
95
+
96
+ def load_test_pairs(seed):
97
+ """Load test pairs with labels: list of (cand_id, index_id, label)"""
98
+ test_path = (f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_"
99
+ f"neg_samples_num=2_vector_normalization=True_seed={seed}.joblib")
100
+ prop = joblib.load(test_path)
101
+
102
+ partition = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb'))
103
+ test_pairs = partition['test']['matching']['negative_sampling']['medium'][2]
104
+
105
+ # Build cand/index ID -> vector mappings
106
+ cand_map = {}
107
+ for bid in prop[PROPERTY_NAMES[0]]['cands'].keys():
108
+ vec = []
109
+ for pname in PROPERTY_NAMES:
110
+ val = prop[pname]['cands'].get(bid, None)
111
+ if val is None or (isinstance(val, float) and np.isnan(val)):
112
+ val = 0.0
113
+ vec.append(float(val))
114
+ cand_map[bid] = np.array(vec, dtype=np.float32)
115
+
116
+ index_map = {}
117
+ for bid in prop[PROPERTY_NAMES[0]]['index'].keys():
118
+ vec = []
119
+ for pname in PROPERTY_NAMES:
120
+ val = prop[pname]['index'].get(bid, None)
121
+ if val is None or (isinstance(val, float) and np.isnan(val)):
122
+ val = 0.0
123
+ vec.append(float(val))
124
+ index_map[bid] = np.array(vec, dtype=np.float32)
125
+
126
+ cand_vecs, index_vecs, labels = [], [], []
127
+ for cid, iid in test_pairs:
128
+ if cid in cand_map and iid in index_map:
129
+ cand_vecs.append(cand_map[cid])
130
+ index_vecs.append(index_map[iid])
131
+ labels.append(1 if cid == iid else 0)
132
+
133
+ cand_vecs = np.array(cand_vecs, dtype=np.float32)
134
+ index_vecs = np.array(index_vecs, dtype=np.float32)
135
+ labels = np.array(labels, dtype=np.int32)
136
+
137
+ print(f"Test pairs: {len(labels)} ({labels.sum()} pos, {(1-labels).sum()} neg)")
138
+ return cand_vecs, index_vecs, labels
139
+
140
+
141
+ # ============================================================
142
+ # Diffusion Model (DDPM on property vectors)
143
+ # ============================================================
144
+ class MLPDiffusion(nn.Module):
145
+ def __init__(self, dim, hidden=256, layers=4):
146
+ super().__init__()
147
+ self.time_embed = nn.Sequential(
148
+ nn.Linear(1, hidden), nn.SiLU(), nn.Linear(hidden, hidden))
149
+ net = [nn.Linear(dim + hidden, hidden), nn.SiLU()]
150
+ for _ in range(layers - 1):
151
+ net += [nn.Linear(hidden, hidden), nn.SiLU()]
152
+ net.append(nn.Linear(hidden, dim))
153
+ self.net = nn.Sequential(*net)
154
+
155
+ def forward(self, x, t):
156
+ t_emb = self.time_embed(t.unsqueeze(-1).float())
157
+ return self.net(torch.cat([x, t_emb], dim=-1))
158
+
159
+
160
+ class DiffusionScheduler:
161
+ def __init__(self, steps=1000, beta_start=1e-4, beta_end=0.02):
162
+ self.steps = steps
163
+ self.betas = torch.linspace(beta_start, beta_end, steps)
164
+ self.alphas = 1 - self.betas
165
+ self.alpha_bars = torch.cumprod(self.alphas, dim=0)
166
+
167
+ def add_noise(self, x0, t):
168
+ ab = self.alpha_bars[t].view(-1, 1)
169
+ noise = torch.randn_like(x0)
170
+ return torch.sqrt(ab) * x0 + torch.sqrt(1 - ab) * noise, noise
171
+
172
+ @torch.no_grad()
173
+ def denoise_step(self, model, xt, t):
174
+ """Single DDPM reverse step"""
175
+ a = self.alphas[t].view(-1, 1)
176
+ ab = self.alpha_bars[t].view(-1, 1)
177
+ b = self.betas[t].view(-1, 1)
178
+ eps = model(xt, t.float())
179
+ x0_hat = (xt - torch.sqrt(1 - ab) * eps) / torch.sqrt(a)
180
+ if t.min() == 0:
181
+ return x0_hat
182
+ ab_prev = self.alpha_bars[t - 1].view(-1, 1)
183
+ mean = (torch.sqrt(ab_prev) * b / (1 - ab) * x0_hat +
184
+ torch.sqrt(a) * (1 - ab_prev) / (1 - ab) * xt)
185
+ var = b * (1 - ab_prev) / (1 - ab)
186
+ return mean + torch.sqrt(var) * torch.randn_like(xt)
187
+
188
+ @torch.no_grad()
189
+ def sdedit(self, model, x0, t0, device):
190
+ """Add noise to t0, then denoise back → sibling"""
191
+ n = x0.shape[0]
192
+ t0_t = torch.full((n,), t0, device=device, dtype=torch.long)
193
+ ab_t0 = self.alpha_bars[t0]
194
+ noise = torch.randn_like(x0)
195
+ xt = torch.sqrt(ab_t0) * x0 + torch.sqrt(1 - ab_t0) * noise
196
+ for t in range(t0, -1, -1):
197
+ tb = torch.full((n,), t, device=device, dtype=torch.long)
198
+ xt = self.denoise_step(model, xt, tb)
199
+ return xt
200
+
201
+
202
+ # ============================================================
203
+ # Contrastive Encoder
204
+ # ============================================================
205
+ class BuildingEncoder(nn.Module):
206
+ def __init__(self, dim, hidden=128, out_dim=64):
207
+ super().__init__()
208
+ self.net = nn.Sequential(
209
+ nn.Linear(dim, hidden), nn.BatchNorm1d(hidden), nn.ReLU(),
210
+ nn.Linear(hidden, hidden), nn.BatchNorm1d(hidden), nn.ReLU(),
211
+ nn.Linear(hidden, out_dim))
212
+
213
+ def forward(self, x):
214
+ return F.normalize(self.net(x), dim=-1)
215
+
216
+
217
+ def info_nce_loss(embs, temp=0.07):
218
+ """embs: [2B, D] where (0,1), (2,3)... are positives"""
219
+ n = embs.shape[0] // 2
220
+ sim = embs @ embs.T / temp
221
+ # Mask self
222
+ sim = sim.masked_fill(torch.eye(2 * n, device=embs.device, dtype=torch.bool), -1e9)
223
+ # Labels: for row i, positive is i^1 (flip last bit)
224
+ labels = torch.arange(2 * n, device=embs.device)
225
+ labels = labels ^ 1 # (0->1, 1->0, 2->3, 3->2, ...)
226
+ return F.cross_entropy(sim, labels)
227
+
228
+
229
+ # ============================================================
230
+ # Training
231
+ # ============================================================
232
+ def train_diffusion(X, device):
233
+ print("\n" + "=" * 50)
234
+ print("Stage 1: Train Diffusion on Building Vectors")
235
+ print("=" * 50)
236
+ dim = X.shape[1]
237
+ model = MLPDiffusion(dim, CFG['diffusion_hidden'], CFG['diffusion_layers']).to(device)
238
+ sched = DiffusionScheduler(CFG['diffusion_steps'])
239
+ sched.betas = sched.betas.to(device)
240
+ sched.alphas = sched.alphas.to(device)
241
+ sched.alpha_bars = sched.alpha_bars.to(device)
242
+
243
+ opt = torch.optim.Adam(model.parameters(), lr=CFG['diffusion_lr'])
244
+ ds = TensorDataset(torch.FloatTensor(X))
245
+ dl = DataLoader(ds, batch_size=CFG['diffusion_batch_size'], shuffle=True)
246
+
247
+ model.train()
248
+ for ep in range(CFG['diffusion_epochs']):
249
+ total = 0
250
+ for (xb,) in dl:
251
+ xb = xb.to(device)
252
+ bs = xb.shape[0]
253
+ t = torch.randint(0, CFG['diffusion_steps'], (bs,), device=device)
254
+ xt, noise = sched.add_noise(xb, t)
255
+ loss = F.mse_loss(model(xt, t.float()), noise)
256
+ opt.zero_grad()
257
+ loss.backward()
258
+ opt.step()
259
+ total += loss.item() * bs
260
+ if (ep + 1) % 100 == 0:
261
+ print(f" Epoch {ep+1}/{CFG['diffusion_epochs']} | Loss: {total/len(ds):.6f}")
262
+ print(f" Done. Final loss: {total/len(ds):.6f}")
263
+ return model, sched
264
+
265
+
266
+ def generate_siblings(model, sched, X, device):
267
+ print("\n" + "=" * 50)
268
+ print(f"Stage 2: Generate Siblings (t0={CFG['sdedit_t0']})")
269
+ print("=" * 50)
270
+ model.eval()
271
+ origs, sibs = [], []
272
+ bs = CFG['diffusion_batch_size']
273
+ for i in range(0, len(X), bs):
274
+ xb = torch.FloatTensor(X[i:i+bs]).to(device)
275
+ for _ in range(CFG['num_siblings']):
276
+ sib = sched.sdedit(model, xb, CFG['sdedit_t0'], device)
277
+ origs.append(xb.cpu().numpy())
278
+ sibs.append(sib.cpu().numpy())
279
+
280
+ origs = np.concatenate(origs, axis=0)
281
+ sibs = np.concatenate(sibs, axis=0)
282
+ l2 = np.mean(np.linalg.norm(origs - sibs, axis=1))
283
+ print(f" Generated {len(origs)} pairs | Mean L2 diff: {l2:.4f}")
284
+ return origs, sibs
285
+
286
+
287
+ def train_encoder(origs, sibs, device):
288
+ print("\n" + "=" * 50)
289
+ print("Stage 3: Contrastive Encoder Training")
290
+ print("=" * 50)
291
+ dim = origs.shape[1]
292
+ encoder = BuildingEncoder(dim, CFG['encoder_hidden'], CFG['encoder_dim']).to(device)
293
+ opt = torch.optim.Adam(encoder.parameters(), lr=CFG['contrastive_lr'])
294
+
295
+ # Interleave: [orig1, sib1, orig2, sib2, ...]
296
+ n = len(origs)
297
+ data = np.zeros((n * 2, dim), dtype=np.float32)
298
+ data[0::2] = origs
299
+ data[1::2] = sibs
300
+ ds = TensorDataset(torch.FloatTensor(data))
301
+ dl = DataLoader(ds, batch_size=CFG['contrastive_batch'], shuffle=True)
302
+
303
+ encoder.train()
304
+ for ep in range(CFG['contrastive_epochs']):
305
+ total = 0
306
+ for (xb,) in dl:
307
+ xb = xb.to(device)
308
+ emb = encoder(xb)
309
+ loss = info_nce_loss(emb, CFG['contrastive_temp'])
310
+ opt.zero_grad()
311
+ loss.backward()
312
+ opt.step()
313
+ total += loss.item() * xb.shape[0]
314
+ if (ep + 1) % 50 == 0:
315
+ print(f" Epoch {ep+1}/{CFG['contrastive_epochs']} | Loss: {total/len(ds):.4f}")
316
+ print(f" Done. Final loss: {total/len(ds):.4f}")
317
+ return encoder
318
+
319
+
320
+ # ============================================================
321
+ # Evaluation
322
+ # ============================================================
323
+ @torch.no_grad()
324
+ def eval_zero_shot(encoder, cand_vecs, index_vecs, labels, device, tag="Model"):
325
+ """Zero-shot pair classification via cosine similarity"""
326
+ encoder.eval()
327
+ ct = torch.FloatTensor(cand_vecs).to(device)
328
+ it = torch.FloatTensor(index_vecs).to(device)
329
+ ce = encoder(ct).cpu().numpy()
330
+ ie = encoder(it).cpu().numpy()
331
+
332
+ # Cosine sim for each pair
333
+ sims = np.sum(ce * ie, axis=1) # [N]
334
+
335
+ # Sweep thresholds
336
+ best_f1, best_thresh, best_res = 0, 0.5, None
337
+ for th in CFG['eval_thresholds']:
338
+ pred = (sims >= th).astype(np.int32)
339
+ p = precision_score(labels, pred, zero_division=0)
340
+ r = recall_score(labels, pred, zero_division=0)
341
+ f = f1_score(labels, pred, zero_division=0)
342
+ if f > best_f1:
343
+ best_f1, best_thresh, best_res = f, th, (p, r, f)
344
+
345
+ print(f"\n {tag} (best threshold={best_thresh:.2f}):")
346
+ print(f" Precision: {best_res[0]:.4f}")
347
+ print(f" Recall: {best_res[1]:.4f}")
348
+ print(f" F1: {best_res[2]:.4f}")
349
+
350
+ # Also AP score
351
+ ap = average_precision_score(labels, sims)
352
+ print(f" AvgPrecision: {ap:.4f}")
353
+
354
+ return {'precision': best_res[0], 'recall': best_res[1], 'f1': best_res[2],
355
+ 'ap': ap, 'threshold': best_thresh}
356
+
357
+
358
+ def eval_real_only(cand_vecs, index_vecs, labels):
359
+ """Baseline: raw property cosine similarity, no training"""
360
+ # Normalize
361
+ cn = cand_vecs / (np.linalg.norm(cand_vecs, axis=1, keepdims=True) + 1e-8)
362
+ i_n = index_vecs / (np.linalg.norm(index_vecs, axis=1, keepdims=True) + 1e-8)
363
+ sims = np.sum(cn * i_n, axis=1)
364
+
365
+ best_f1, best_thresh, best_res = 0, 0.5, None
366
+ for th in CFG['eval_thresholds']:
367
+ pred = (sims >= th).astype(np.int32)
368
+ p = precision_score(labels, pred, zero_division=0)
369
+ r = recall_score(labels, pred, zero_division=0)
370
+ f = f1_score(labels, pred, zero_division=0)
371
+ if f > best_f1:
372
+ best_f1, best_thresh, best_res = f, th, (p, r, f)
373
+
374
+ ap = average_precision_score(labels, sims)
375
+ print(f"\n Baseline Real-Only (best th={best_thresh:.2f}):")
376
+ print(f" P={best_res[0]:.4f} R={best_res[1]:.4f} F1={best_res[2]:.4f} AP={ap:.4f}")
377
+
378
+ return {'precision': best_res[0], 'recall': best_res[1], 'f1': best_res[2],
379
+ 'ap': ap, 'threshold': best_thresh}
380
+
381
+
382
+ # ============================================================
383
+ # Main
384
+ # ============================================================
385
+ def main():
386
+ parser = argparse.ArgumentParser()
387
+ parser.add_argument('--seed', type=int, default=1)
388
+ parser.add_argument('--t0', type=int, default=200, help='SDEdit noise level')
389
+ parser.add_argument('--skip_diff', action='store_true')
390
+ parser.add_argument('--skip_enc', action='store_true')
391
+ args = parser.parse_args()
392
+
393
+ CFG['sdedit_t0'] = args.t0
394
+ device = CFG['device']
395
+ seed = args.seed
396
+ print(f"Device: {device} | t0: {args.t0} | Seed: {seed}")
397
+
398
+ # ---- Load data ----
399
+ X_train, train_ids, train_prop = load_all_train_vectors(seed)
400
+ cand_vecs, idx_vecs, labels = load_test_pairs(seed)
401
+
402
+ # Normalize (fit on train, apply to test)
403
+ scaler = StandardScaler()
404
+ X_train_s = scaler.fit_transform(X_train)
405
+ cand_s = scaler.transform(cand_vecs)
406
+ idx_s = scaler.transform(idx_vecs)
407
+
408
+ # ---- Stage 1+2: Diffusion → Siblings ----
409
+ diff_path = f"saved_model_files/diff_idea3_s{seed}_t{args.t0}.pt"
410
+ sib_path = f"saved_model_files/siblings_idea3_s{seed}_t{args.t0}.npz"
411
+
412
+ if args.skip_diff and os.path.exists(diff_path):
413
+ print(f"Loading cached diffusion model: {diff_path}")
414
+ ck = torch.load(diff_path, map_location=device)
415
+ model = MLPDiffusion(X_train_s.shape[1], CFG['diffusion_hidden'],
416
+ CFG['diffusion_layers']).to(device)
417
+ model.load_state_dict(ck['model'])
418
+ sched = DiffusionScheduler(CFG['diffusion_steps'])
419
+ sched.betas = sched.betas.to(device)
420
+ sched.alphas = sched.alphas.to(device)
421
+ sched.alpha_bars = sched.alpha_bars.to(device)
422
+ else:
423
+ model, sched = train_diffusion(X_train_s, device)
424
+ torch.save({'model': model.state_dict()}, diff_path)
425
+
426
+ if os.path.exists(sib_path):
427
+ print(f"Loading cached siblings: {sib_path}")
428
+ data = np.load(sib_path)
429
+ origs, sibs = data['origs'], data['sibs']
430
+ else:
431
+ origs, sibs = generate_siblings(model, sched, X_train_s, device)
432
+ np.savez_compressed(sib_path, origs=origs, sibs=sibs)
433
+
434
+ # ---- Stage 3: Contrastive Encoder ----
435
+ enc_path = f"saved_model_files/enc_idea3_s{seed}_t{args.t0}.pt"
436
+
437
+ if args.skip_enc and os.path.exists(enc_path):
438
+ print(f"Loading cached encoder: {enc_path}")
439
+ ck = torch.load(enc_path, map_location=device)
440
+ encoder = BuildingEncoder(X_train_s.shape[1], CFG['encoder_hidden'],
441
+ CFG['encoder_dim']).to(device)
442
+ encoder.load_state_dict(ck['encoder'])
443
+ else:
444
+ encoder = train_encoder(origs, sibs, device)
445
+ torch.save({'encoder': encoder.state_dict()}, enc_path)
446
+
447
+ # ---- Evaluation ----
448
+ print("\n" + "=" * 50)
449
+ print("RESULTS")
450
+ print("=" * 50)
451
+
452
+ r_base = eval_real_only(cand_s, idx_s, labels)
453
+ r_idea3 = eval_zero_shot(encoder, cand_s, idx_s, labels, device,
454
+ f"Idea 3 (t0={args.t0})")
455
+
456
+ print("\n" + "=" * 50)
457
+ print(f"SUMMARY (seed={seed}, t0={args.t0})")
458
+ print("=" * 50)
459
+ print(f" Baseline (real-only): F1={r_base['f1']:.4f} AP={r_base['ap']:.4f}")
460
+ print(f" Idea 3 (denoise-sib): F1={r_idea3['f1']:.4f} AP={r_idea3['ap']:.4f}")
461
+ print(f" ΔF1: {r_idea3['f1'] - r_base['f1']:.4f} ΔAP: {r_idea3['ap'] - r_base['ap']:.4f}")
462
+
463
+ return r_base, r_idea3
464
+
465
+
466
+ if __name__ == '__main__':
467
+ main()
code/ster_gi_idea3_v2.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ STER-GI Idea 3: Denoise-to-Sibling
3
+ - Train: diffusion + contrastive on ALL building vectors (NO labels)
4
+ - Eval: ALL train+test pairs, zero-shot cosine similarity → F1
5
+ """
6
+ import numpy as np, joblib, pickle as pkl, torch, torch.nn as nn, torch.nn.functional as F, time, os, argparse
7
+ from torch.utils.data import DataLoader, TensorDataset
8
+ from sklearn.preprocessing import StandardScaler
9
+ from sklearn.metrics import precision_score, recall_score, f1_score
10
+
11
+ PROPS = ["bounding_box_width","bounding_box_length","area","perimeter","perimeter_ind",
12
+ "volume","convex_hull_area","convex_hull_volume","ave_centroid_distance","height_diff",
13
+ "num_floors","axes_symmetry","compactness_2d","compactness_3d","density","elongation",
14
+ "shape_ind","hemisphericality","fractality","cubeness","circumference",
15
+ "aligned_bounding_box_width","aligned_bounding_box_length","aligned_bounding_box_height","num_vertices"]
16
+
17
+ CFG = {'diff_steps':1000,'diff_hidden':256,'diff_layers':4,'diff_epochs':100,'diff_lr':1e-3,'diff_bs':512,
18
+ 't0':200,'n_sib':2,'enc_hidden':128,'enc_dim':64,'ctr_epochs':100,'ctr_lr':1e-3,'ctr_temp':0.07,'ctr_bs':1024}
19
+
20
+ # ---------- Data ----------
21
+ def get_vecs(prop_dict, source):
22
+ ids = list(prop_dict[PROPS[0]][source].keys())
23
+ X = np.zeros((len(ids), len(PROPS)), dtype=np.float32)
24
+ for i, bid in enumerate(ids):
25
+ for j, pn in enumerate(PROPS):
26
+ v = prop_dict[pn][source].get(bid, None)
27
+ X[i,j] = float(v) if v is not None and not (isinstance(v,float) and np.isnan(v)) else 0.0
28
+ return X, ids
29
+
30
+ def load_all_data(seed):
31
+ """Load ALL building vectors (train+test) and ALL pairs (train+test)"""
32
+ # Train buildings
33
+ tp = f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib"
34
+ trp = joblib.load(tp)
35
+ Xtc, id_tc = get_vecs(trp, 'cands')
36
+ Xti, id_ti = get_vecs(trp, 'index')
37
+ X_all = np.concatenate([Xtc, Xti], axis=0)
38
+ print(f"Train buildings: {len(Xtc)} cands + {len(Xti)} index = {len(X_all)}", flush=True)
39
+
40
+ # Test buildings
41
+ ep = f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib"
42
+ epd = joblib.load(ep)
43
+ Xec, id_ec = get_vecs(epd, 'cands')
44
+ Xei, id_ei = get_vecs(epd, 'index')
45
+
46
+ # Combine ALL building vectors (for diffusion training)
47
+ X_all = np.concatenate([X_all, Xec, Xei], axis=0)
48
+ print(f"All buildings for diffusion: {len(X_all)}", flush=True)
49
+
50
+ # ALL pairs (train+test) for evaluation
51
+ part = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb'))
52
+ train_pairs = part['train']['negative_sampling']['medium'][2]
53
+ test_pairs = part['test']['matching']['negative_sampling']['medium'][2]
54
+ all_pairs = list(train_pairs) + list(test_pairs)
55
+
56
+ # Build lookup for all buildings
57
+ cand_map = {}
58
+ for src_prop, src_ids in [(trp,id_tc), (epd,id_ec)]:
59
+ for bid in src_ids:
60
+ if bid not in cand_map:
61
+ v = [float(src_prop[pn]['cands'].get(bid,0) or 0) for pn in PROPS]
62
+ cand_map[bid] = np.array(v, dtype=np.float32)
63
+ index_map = {}
64
+ for src_prop, src_ids in [(trp,id_ti), (epd,id_ei)]:
65
+ for bid in src_ids:
66
+ if bid not in index_map:
67
+ v = [float(src_prop[pn]['index'].get(bid,0) or 0) for pn in PROPS]
68
+ index_map[bid] = np.array(v, dtype=np.float32)
69
+
70
+ # Build pair vectors + labels
71
+ cv, iv, lbs = [], [], []
72
+ for cid, iid in all_pairs:
73
+ if cid in cand_map and iid in index_map:
74
+ cv.append(cand_map[cid])
75
+ iv.append(index_map[iid])
76
+ lbs.append(1 if cid == iid else 0)
77
+ cv, iv, lbs = np.array(cv,dtype=np.float32), np.array(iv,dtype=np.float32), np.array(lbs,dtype=np.int32)
78
+ print(f"All eval pairs: {len(lbs)} ({lbs.sum()} pos, {(1-lbs).sum()} neg)", flush=True)
79
+ return X_all, cv, iv, lbs
80
+
81
+ # ---------- Diffusion ----------
82
+ class DiffMLP(nn.Module):
83
+ def __init__(self,d,h=256,L=4):
84
+ super().__init__()
85
+ self.te = nn.Sequential(nn.Linear(1,h),nn.SiLU(),nn.Linear(h,h))
86
+ net = [nn.Linear(d+h,h),nn.SiLU()]
87
+ for _ in range(L-1): net += [nn.Linear(h,h),nn.SiLU()]
88
+ net.append(nn.Linear(h,d))
89
+ self.net = nn.Sequential(*net)
90
+ def forward(self,x,t):
91
+ return self.net(torch.cat([x,self.te(t.unsqueeze(-1).float())],-1))
92
+
93
+ class DiffSched:
94
+ def __init__(self,S=1000):
95
+ self.S=S; self.b=torch.linspace(1e-4,0.02,S); self.a=1-self.b; self.ab=torch.cumprod(self.a,0)
96
+ def noise(self,x0,t):
97
+ ab=self.ab[t].view(-1,1); eps=torch.randn_like(x0)
98
+ return torch.sqrt(ab)*x0+torch.sqrt(1-ab)*eps, eps
99
+ @torch.no_grad()
100
+ def step(self,m,xt,t):
101
+ a=self.a[t].view(-1,1); ab=self.ab[t].view(-1,1); b_=self.b[t].view(-1,1)
102
+ e=m(xt,t.float()); x0h=(xt-torch.sqrt(1-ab)*e)/torch.sqrt(a)
103
+ if t.min()==0: return x0h
104
+ abp=self.ab[t-1].view(-1,1)
105
+ mu=torch.sqrt(abp)*b_/(1-ab)*x0h+torch.sqrt(a)*(1-abp)/(1-ab)*xt
106
+ return mu+torch.sqrt(b_*(1-abp)/(1-ab))*torch.randn_like(xt)
107
+ @torch.no_grad()
108
+ def sdedit(self,m,x0,t0,dev):
109
+ n=x0.shape[0]; abt=self.ab[t0]
110
+ xt=torch.sqrt(abt)*x0+torch.sqrt(1-abt)*torch.randn_like(x0)
111
+ for t in range(t0,-1,-1):
112
+ xt=self.step(m,xt,torch.full((n,),t,device=dev,dtype=torch.long))
113
+ return xt
114
+
115
+ # ---------- Encoder ----------
116
+ class Encoder(nn.Module):
117
+ def __init__(self,d,h=128,o=64):
118
+ super().__init__()
119
+ self.net=nn.Sequential(nn.Linear(d,h),nn.BatchNorm1d(h),nn.ReLU(),
120
+ nn.Linear(h,h),nn.BatchNorm1d(h),nn.ReLU(),nn.Linear(h,o))
121
+ def forward(self,x): return F.normalize(self.net(x),-1)
122
+
123
+ def infonce(emb,temp=0.07):
124
+ n=emb.shape[0]//2; sim=emb@emb.T/temp
125
+ sim=sim.masked_fill(torch.eye(2*n,device=emb.device,dtype=torch.bool),-1e9)
126
+ return F.cross_entropy(sim,torch.arange(2*n,device=emb.device)^1)
127
+
128
+ # ---------- Eval ----------
129
+ def eval_pairs(encoder, cv, iv, lbs, dev, tag=""):
130
+ encoder.eval()
131
+ with torch.no_grad():
132
+ ce = encoder(torch.FloatTensor(cv).to(dev)).cpu().numpy()
133
+ ie = encoder(torch.FloatTensor(iv).to(dev)).cpu().numpy()
134
+ sims = np.sum(ce * ie, axis=1)
135
+ best_f1, best_th = 0, 0
136
+ for th in np.arange(0.3, 1.0, 0.02):
137
+ pred = (sims >= th).astype(np.int32)
138
+ f = f1_score(lbs, pred, zero_division=0)
139
+ if f > best_f1: best_f1, best_th = f, th
140
+ p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
141
+ r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
142
+ print(f" {tag}: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True)
143
+ return best_f1
144
+
145
+ def baseline_raw(cv, iv, lbs):
146
+ cn = cv/(np.linalg.norm(cv,axis=1,keepdims=True)+1e-8)
147
+ i_n = iv/(np.linalg.norm(iv,axis=1,keepdims=True)+1e-8)
148
+ sims = np.sum(cn * i_n, axis=1)
149
+ best_f1, best_th = 0, 0
150
+ for th in np.arange(0.3, 1.0, 0.02):
151
+ pred = (sims >= th).astype(np.int32)
152
+ f = f1_score(lbs, pred, zero_division=0)
153
+ if f > best_f1: best_f1, best_th = f, th
154
+ p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
155
+ r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
156
+ print(f" Baseline Raw: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True)
157
+ return best_f1
158
+
159
+ # ---------- Main ----------
160
+ def main():
161
+ p = argparse.ArgumentParser()
162
+ p.add_argument('--seed',type=int,default=1)
163
+ p.add_argument('--t0',type=int,default=200)
164
+ p.add_argument('--skip_diff',action='store_true')
165
+ p.add_argument('--skip_enc',action='store_true')
166
+ a = p.parse_args()
167
+ CFG['t0']=a.t0
168
+ dev = 'cuda' if torch.cuda.is_available() else 'cpu'
169
+ print(f"Device: {dev} | t0: {a.t0} | Seed: {a.seed}", flush=True)
170
+
171
+ # Load
172
+ X_all, cv, iv, lbs = load_all_data(a.seed)
173
+ sc = StandardScaler(); Xs = sc.fit_transform(X_all)
174
+ cv_s, iv_s = sc.transform(cv), sc.transform(iv)
175
+
176
+ # Baseline
177
+ print("\n=== Zero-Shot Baseline ===")
178
+ b_raw = baseline_raw(cv_s, iv_s, lbs)
179
+
180
+ # Diffusion
181
+ diff_path = f"saved_model_files/diff_i3_s{a.seed}_t{a.t0}.pt"
182
+ sib_path = f"saved_model_files/sib_i3_s{a.seed}_t{a.t0}.npz"
183
+ if a.skip_diff and os.path.exists(diff_path):
184
+ ck = torch.load(diff_path, map_location=dev)
185
+ model = DiffMLP(Xs.shape[1], CFG['diff_hidden'], CFG['diff_layers']).to(dev)
186
+ model.load_state_dict(ck['m'])
187
+ sched = DiffSched(CFG['diff_steps'])
188
+ for attr in ['b','a','ab']: setattr(sched, attr, getattr(sched, attr).to(dev))
189
+ else:
190
+ print("\n=== Training Diffusion ===")
191
+ model = DiffMLP(Xs.shape[1], CFG['diff_hidden'], CFG['diff_layers']).to(dev)
192
+ sched = DiffSched(CFG['diff_steps'])
193
+ for attr in ['b','a','ab']: setattr(sched, attr, getattr(sched, attr).to(dev))
194
+ opt = torch.optim.Adam(model.parameters(), lr=CFG['diff_lr'])
195
+ ds = TensorDataset(torch.FloatTensor(Xs)); dl = DataLoader(ds, batch_size=CFG['diff_bs'], shuffle=True)
196
+ model.train()
197
+ for ep in range(CFG['diff_epochs']):
198
+ tot = 0
199
+ for (xb,) in dl:
200
+ xb = xb.to(dev); bs = xb.shape[0]
201
+ t = torch.randint(0, CFG['diff_steps'], (bs,), device=dev)
202
+ xt, noise = sched.noise(xb, t)
203
+ loss = F.mse_loss(model(xt, t.float()), noise)
204
+ opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()*bs
205
+ if (ep+1)%10==0: print(f" Diff ep {ep+1}/{CFG['diff_epochs']}: loss={tot/len(ds):.6f}", flush=True)
206
+ print(f" Done: loss={tot/len(ds):.6f}", flush=True)
207
+ torch.save({'m':model.state_dict()}, diff_path)
208
+
209
+ # Siblings
210
+ if os.path.exists(sib_path):
211
+ d = np.load(sib_path); origs, sibs = d['o'], d['s']
212
+ else:
213
+ print("\n=== Generating Siblings ===")
214
+ model.eval(); origs, sibs = [], []
215
+ with torch.no_grad():
216
+ for i in range(0, len(Xs), CFG['diff_bs']):
217
+ xb = torch.FloatTensor(Xs[i:i+CFG['diff_bs']]).to(dev)
218
+ for _ in range(CFG['n_sib']):
219
+ sib = sched.sdedit(model, xb, CFG['t0'], dev)
220
+ origs.append(xb.cpu().numpy()); sibs.append(sib.cpu().numpy())
221
+ origs = np.concatenate(origs); sibs = np.concatenate(sibs)
222
+ print(f" {len(origs)} pairs, mean L2 diff: {np.mean(np.linalg.norm(origs-sibs,axis=1)):.4f}", flush=True)
223
+ np.savez_compressed(sib_path, o=origs, s=sibs)
224
+
225
+ # Encoder
226
+ enc_path = f"saved_model_files/enc_i3_s{a.seed}_t{a.t0}.pt"
227
+ if a.skip_enc and os.path.exists(enc_path):
228
+ ck = torch.load(enc_path, map_location=dev)
229
+ encoder = Encoder(Xs.shape[1], CFG['enc_hidden'], CFG['enc_dim']).to(dev)
230
+ encoder.load_state_dict(ck['e'])
231
+ else:
232
+ print("\n=== Training Encoder ===")
233
+ encoder = Encoder(Xs.shape[1], CFG['enc_hidden'], CFG['enc_dim']).to(dev)
234
+ opt = torch.optim.Adam(encoder.parameters(), lr=CFG['ctr_lr'])
235
+ n = len(origs)
236
+ # Shuffle pairs (not individual samples) to keep (orig, sib) adjacent
237
+ pair_idx = np.random.permutation(n)
238
+ origs_shuffled = origs[pair_idx]
239
+ sibs_shuffled = sibs[pair_idx]
240
+ data = np.zeros((n*2, Xs.shape[1]), dtype=np.float32)
241
+ data[0::2]=origs_shuffled; data[1::2]=sibs_shuffled
242
+ ds = TensorDataset(torch.FloatTensor(data)); dl = DataLoader(ds, batch_size=CFG['ctr_bs'], shuffle=False)
243
+ encoder.train()
244
+ for ep in range(CFG['ctr_epochs']):
245
+ tot = 0
246
+ for (xb,) in dl:
247
+ xb = xb.to(dev); emb = encoder(xb); loss = infonce(emb, CFG['ctr_temp'])
248
+ opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()*xb.shape[0]
249
+ if (ep+1)%10==0: print(f" Enc ep {ep+1}/{CFG['ctr_epochs']}: loss={tot/len(ds):.4f}", flush=True)
250
+ print(f" Done: loss={tot/len(ds):.4f}", flush=True)
251
+ torch.save({'e':encoder.state_dict()}, enc_path)
252
+
253
+ # Eval
254
+ print("\n=== Results ===")
255
+ eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea3 (t0={a.t0})")
256
+ print(f"\n Baseline (raw props): F1={b_raw:.4f}", flush=True)
257
+ print(f" Supervised XGBoost ref: F1=0.982", flush=True)
258
+
259
+ # Patched
260
+ if __name__=='__main__': main()
261
+ sibs_shuffled = sibs[pair_idx]
262
+ in()
code/ster_gi_idea3_v3.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """STER-GI Idea 3: Denoise-to-Sibling — Zero-Shot 3D GER"""
2
+ import numpy as np, joblib, pickle as pkl, torch, torch.nn as nn, torch.nn.functional as F, time, os, argparse, sys
3
+ from torch.utils.data import DataLoader, TensorDataset
4
+ from sklearn.preprocessing import StandardScaler
5
+ from sklearn.metrics import precision_score, recall_score, f1_score
6
+
7
+ PROPS = ["bounding_box_width","bounding_box_length","area","perimeter","perimeter_ind",
8
+ "volume","convex_hull_area","convex_hull_volume","ave_centroid_distance","height_diff",
9
+ "num_floors","axes_symmetry","compactness_2d","compactness_3d","density","elongation",
10
+ "shape_ind","hemisphericality","fractality","cubeness","circumference",
11
+ "aligned_bounding_box_width","aligned_bounding_box_length","aligned_bounding_box_height","num_vertices"]
12
+
13
+ # ===== Data =====
14
+ def get_vecs(prop_dict, source):
15
+ ids = list(prop_dict[PROPS[0]][source].keys())
16
+ X = np.zeros((len(ids), len(PROPS)), dtype=np.float32)
17
+ for i, bid in enumerate(ids):
18
+ for j, pn in enumerate(PROPS):
19
+ v = prop_dict[pn][source].get(bid, None)
20
+ X[i,j] = float(v) if v is not None and not (isinstance(v,float) and np.isnan(v)) else 0.0
21
+ return X, ids
22
+
23
+ def load_all(seed):
24
+ tp = f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib"
25
+ ep = f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib"
26
+ trp = joblib.load(tp); epd = joblib.load(ep)
27
+ Xtc, id_tc = get_vecs(trp, 'cands'); Xti, id_ti = get_vecs(trp, 'index')
28
+ Xec, id_ec = get_vecs(epd, 'cands'); Xei, id_ei = get_vecs(epd, 'index')
29
+ X_all = np.concatenate([Xtc, Xti, Xec, Xei], axis=0)
30
+ print(f"Buildings: {len(X_all)} (train cands={len(Xtc)} index={len(Xti)} test cands={len(Xec)} index={len(Xei)})", flush=True)
31
+
32
+ part = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb'))
33
+ all_pairs = list(part['train']['negative_sampling']['medium'][2]) + list(part['test']['matching']['negative_sampling']['medium'][2])
34
+
35
+ cand_map, index_map = {}, {}
36
+ for sp, ids in [(trp,id_tc),(epd,id_ec)]:
37
+ for bid in ids:
38
+ if bid not in cand_map:
39
+ cand_map[bid] = np.array([float(sp[pn]['cands'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32)
40
+ for sp, ids in [(trp,id_ti),(epd,id_ei)]:
41
+ for bid in ids:
42
+ if bid not in index_map:
43
+ index_map[bid] = np.array([float(sp[pn]['index'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32)
44
+
45
+ cv, iv, lbs = [], [], []
46
+ for cid, iid in all_pairs:
47
+ if cid in cand_map and iid in index_map:
48
+ cv.append(cand_map[cid]); iv.append(index_map[iid]); lbs.append(1 if cid == iid else 0)
49
+ cv, iv, lbs = np.array(cv,dtype=np.float32), np.array(iv,dtype=np.float32), np.array(lbs,dtype=np.int32)
50
+ print(f"Eval pairs: {len(lbs)} ({lbs.sum()} pos, {(1-lbs).sum()} neg)", flush=True)
51
+ return X_all, cv, iv, lbs
52
+
53
+ # ===== Diffusion =====
54
+ class DiffMLP(nn.Module):
55
+ def __init__(self,d,h=256,L=4):
56
+ super().__init__()
57
+ self.te = nn.Sequential(nn.Linear(1,h),nn.SiLU(),nn.Linear(h,h))
58
+ net = [nn.Linear(d+h,h),nn.SiLU()]
59
+ for _ in range(L-1): net += [nn.Linear(h,h),nn.SiLU()]
60
+ net.append(nn.Linear(h,d)); self.net = nn.Sequential(*net)
61
+ def forward(self,x,t): return self.net(torch.cat([x,self.te(t.unsqueeze(-1).float())],-1))
62
+
63
+ class DiffSched:
64
+ def __init__(self,S=1000):
65
+ self.S=S; self.b=torch.linspace(1e-4,0.02,S); self.a=1-self.b; self.ab=torch.cumprod(self.a,0)
66
+ def noise(self,x0,t):
67
+ ab=self.ab[t].view(-1,1); eps=torch.randn_like(x0)
68
+ return torch.sqrt(ab)*x0+torch.sqrt(1-ab)*eps, eps
69
+ @torch.no_grad()
70
+ def step(self,m,xt,t):
71
+ a=self.a[t].view(-1,1); ab=self.ab[t].view(-1,1); b_=self.b[t].view(-1,1)
72
+ e=m(xt,t.float()); x0h=(xt-torch.sqrt(1-ab)*e)/torch.sqrt(a)
73
+ if t.min()==0: return x0h
74
+ abp=self.ab[t-1].view(-1,1)
75
+ mu=torch.sqrt(abp)*b_/(1-ab)*x0h+torch.sqrt(a)*(1-abp)/(1-ab)*xt
76
+ return mu+torch.sqrt(b_*(1-abp)/(1-ab))*torch.randn_like(xt)
77
+ @torch.no_grad()
78
+ def sdedit(self,m,x0,t0,dev):
79
+ n=x0.shape[0]; xt=torch.sqrt(self.ab[t0])*x0+torch.sqrt(1-self.ab[t0])*torch.randn_like(x0)
80
+ for t in range(t0,-1,-1): xt=self.step(m,xt,torch.full((n,),t,device=dev,dtype=torch.long))
81
+ return xt
82
+
83
+ # ===== Encoder =====
84
+ class Encoder(nn.Module):
85
+ def __init__(self,d,h=128,o=64):
86
+ super().__init__()
87
+ self.net=nn.Sequential(nn.Linear(d,h),nn.BatchNorm1d(h),nn.ReLU(),
88
+ nn.Linear(h,h),nn.BatchNorm1d(h),nn.ReLU(),nn.Linear(h,o))
89
+ def forward(self,x): z = self.net(x); return z / (torch.norm(z, dim=-1, keepdim=True).clamp(min=1e-8))
90
+
91
+ def infonce(emb,temp=0.07):
92
+ n=emb.shape[0]//2; sim=emb@emb.T/temp
93
+ sim=sim.masked_fill(torch.eye(2*n,device=emb.device,dtype=torch.bool),-1e9)
94
+ return F.cross_entropy(sim,torch.arange(2*n,device=emb.device)^1)
95
+
96
+ # ===== Eval =====
97
+ def eval_pairs(encoder, cv, iv, lbs, dev, tag=""):
98
+ encoder.eval()
99
+ with torch.no_grad():
100
+ ce = encoder(torch.FloatTensor(cv).to(dev)).cpu().numpy()
101
+ ie = encoder(torch.FloatTensor(iv).to(dev)).cpu().numpy()
102
+ sims = np.sum(ce * ie, axis=1)
103
+ best_f1, best_th = 0, 0
104
+ for th in np.arange(0.3, 1.0, 0.02):
105
+ pred = (sims >= th).astype(np.int32)
106
+ f = f1_score(lbs, pred, zero_division=0)
107
+ if f > best_f1: best_f1, best_th = f, th
108
+ p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
109
+ r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
110
+ print(f" {tag}: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True)
111
+ return best_f1
112
+
113
+ def baseline_raw(cv, iv, lbs):
114
+ cn = cv/(np.linalg.norm(cv,axis=1,keepdims=True)+1e-8)
115
+ i_n = iv/(np.linalg.norm(iv,axis=1,keepdims=True)+1e-8)
116
+ sims = np.sum(cn * i_n, axis=1)
117
+ best_f1, best_th = 0, 0
118
+ for th in np.arange(0.3, 1.0, 0.02):
119
+ pred = (sims >= th).astype(np.int32)
120
+ f = f1_score(lbs, pred, zero_division=0)
121
+ if f > best_f1: best_f1, best_th = f, th
122
+ p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
123
+ r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0)
124
+ print(f" Baseline Raw: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True)
125
+ return best_f1
126
+
127
+ # ===== Main =====
128
+ def main():
129
+ a = argparse.ArgumentParser()
130
+ a.add_argument('--seed',type=int,default=1); a.add_argument('--t0',type=int,default=200)
131
+ a.add_argument('--skip_diff',action='store_true'); a.add_argument('--skip_enc',action='store_true')
132
+ a.add_argument('--diff_ep',type=int,default=100); a.add_argument('--enc_ep',type=int,default=100)
133
+ args = a.parse_args()
134
+ dev = 'cpu'
135
+ print(f"Device: {dev} | t0: {args.t0} | Seed: {args.seed}", flush=True)
136
+
137
+ X_all, cv, iv, lbs = load_all(args.seed)
138
+ sc = StandardScaler(); Xs = sc.fit_transform(X_all)
139
+ cv_s, iv_s = sc.transform(cv), sc.transform(iv)
140
+
141
+ print("\n=== Baseline ===", flush=True)
142
+ b_raw = baseline_raw(cv_s, iv_s, lbs)
143
+
144
+ # Diffusion
145
+ diff_path = f"saved_model_files/diff_i3_s{args.seed}_t{args.t0}.pt"
146
+ sib_path = f"saved_model_files/sib_i3_s{args.seed}_t{args.t0}.npz"
147
+ if args.skip_diff and os.path.exists(diff_path):
148
+ print(f"Loading cached diffusion: {diff_path}", flush=True)
149
+ ck = torch.load(diff_path, map_location=dev)
150
+ model = DiffMLP(Xs.shape[1]).to(dev); model.load_state_dict(ck['m'])
151
+ sched = DiffSched(); [setattr(sched,x,getattr(sched,x).to(dev)) for x in ['b','a','ab']]
152
+ else:
153
+ print(f"\n=== Diffusion ({args.diff_ep} epochs) ===", flush=True)
154
+ model = DiffMLP(Xs.shape[1]).to(dev); sched = DiffSched()
155
+ [setattr(sched,x,getattr(sched,x).to(dev)) for x in ['b','a','ab']]
156
+ opt = torch.optim.Adam(model.parameters(), lr=1e-3)
157
+ ds = TensorDataset(torch.FloatTensor(Xs)); dl = DataLoader(ds, batch_size=512, shuffle=True)
158
+ model.train(); t0_t = time.time()
159
+ for ep in range(args.diff_ep):
160
+ tot = 0
161
+ for (xb,) in dl:
162
+ xb = xb.to(dev); bs = xb.shape[0]
163
+ t = torch.randint(0, 1000, (bs,), device=dev)
164
+ xt, noise = sched.noise(xb, t)
165
+ loss = F.mse_loss(model(xt, t.float()), noise)
166
+ opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()*bs
167
+ if (ep+1)%10==0: print(f" Diff ep {ep+1}/{args.diff_ep}: loss={tot/len(ds):.6f} t={time.time()-t0_t:.0f}s", flush=True)
168
+ print(f" Done: loss={tot/len(ds):.6f}", flush=True)
169
+ torch.save({'m':model.state_dict()}, diff_path)
170
+
171
+ # Siblings
172
+ if os.path.exists(sib_path):
173
+ d = np.load(sib_path); origs, sibs = d['o'], d['s']
174
+ print(f"Loaded cached siblings: {len(origs)} pairs", flush=True)
175
+ else:
176
+ print("\n=== Generating Siblings ===", flush=True)
177
+ model.eval(); origs, sibs = [], []
178
+ with torch.no_grad():
179
+ for i in range(0, len(Xs), 512):
180
+ xb = torch.FloatTensor(Xs[i:i+512]).to(dev)
181
+ for _ in range(2): # 2 siblings per building
182
+ origs.append(xb.cpu().numpy()); sibs.append(sched.sdedit(model, xb, args.t0, dev).cpu().numpy())
183
+ origs = np.concatenate(origs); sibs = np.concatenate(sibs)
184
+ l2 = np.mean(np.linalg.norm(origs - sibs, axis=1))
185
+ print(f" {len(origs)} pairs, mean L2 diff: {l2:.4f}", flush=True)
186
+ np.savez_compressed(sib_path, o=origs, s=sibs)
187
+
188
+ # Encoder
189
+ enc_path = f"saved_model_files/enc_i3_s{args.seed}_t{args.t0}.pt"
190
+ if args.skip_enc and os.path.exists(enc_path):
191
+ print(f"Loading cached encoder: {enc_path}", flush=True)
192
+ ck = torch.load(enc_path, map_location=dev)
193
+ encoder = Encoder(Xs.shape[1]).to(dev); encoder.load_state_dict(ck['e'])
194
+ else:
195
+ print(f"\n=== Encoder ({args.enc_ep} epochs) ===", flush=True)
196
+ encoder = Encoder(Xs.shape[1]).to(dev)
197
+ opt = torch.optim.Adam(encoder.parameters(), lr=1e-4)
198
+ # Build paired data: shuffle at pair level (NOT sample level)
199
+ n = len(origs); idx = np.random.permutation(n)
200
+ data = np.zeros((n*2, Xs.shape[1]), dtype=np.float32)
201
+ data[0::2] = origs[idx]; data[1::2] = sibs[idx]
202
+ ds = TensorDataset(torch.FloatTensor(data)); dl = DataLoader(ds, batch_size=1024, shuffle=False)
203
+ encoder.train(); t0_t = time.time()
204
+ for ep in range(args.enc_ep):
205
+ tot = 0
206
+ for (xb,) in dl:
207
+ xb = xb.to(dev); emb = encoder(xb); loss = infonce(emb, 0.07)
208
+ opt.zero_grad(); loss.backward(); torch.nn.utils.clip_grad_norm_(encoder.parameters(), 1.0); opt.step(); tot += loss.item()*xb.shape[0]
209
+ if (ep+1)%10==0: print(f" Enc ep {ep+1}/{args.enc_ep}: loss={tot/len(ds):.4f} t={time.time()-t0_t:.0f}s", flush=True)
210
+ print(f" Done: loss={tot/len(ds):.4f}", flush=True)
211
+ torch.save({'e':encoder.state_dict()}, enc_path)
212
+
213
+ # Results
214
+ print("\n=== RESULTS ===", flush=True)
215
+ f1_i3 = eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea3 (t0={args.t0})")
216
+ print(f"\n Baseline (raw): F1={b_raw:.4f}")
217
+ print(f" Idea3 (denoise-sib): F1={f1_i3:.4f}")
218
+ print(f" Supervised XGBoost: F1=0.982 (reference)")
219
+ print(f" Δ over baseline: {f1_i3-b_raw:+.4f}", flush=True)
220
+
221
+ if __name__=='__main__': main()