File size: 50,613 Bytes
bcb16da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
import copy
import json
import os
import config
from utils import *
from blocking import Blocker
from collections import defaultdict
from process_pairs import PairProcessor
from object_properties import ObjectPropertiesProcessor
import numpy as np
from sklearn.model_selection import train_test_split
from classifier import FlexibleClassifier
from abc import ABC, abstractmethod
from multiprocessing import Pool, cpu_count
from disaster_simulation import DisasterSimulator
from alignment import RigidAligner


class PipelineManager:
    def __init__(self, seed, logger, args, min_surfaces_num=10):
        self.dataset_name = args.dataset_name
        self.seed = seed
        self.logger = logger
        self.with_prep_training = args.run_preparatory_phase
        self.min_surfaces_num = min_surfaces_num
        self.evaluation_mode = args.evaluation_mode
        self.blocking_method = args.blocking_method
        self.dataset_size_version = args.dataset_size_version
        self.neg_samples_num = args.neg_samples_num
        self.vector_normalization = args.vector_normalization
        self.sdr_factor = args.sdr_factor
        self.bkafi_criterion = args.bkafi_criterion
        self.matching_cands_generation = args.matching_cands_generation
        self.run_blocker_train = args.run_blocker_train
        self._simulator = None   # set by _read_objects when disaster simulation runs
        self.dataset_dict = self._create_dataset_dict()
        self.flexible_classifier_obj = self._train_and_evaluate()
        self.result_dict = self._get_result_dict()

    def _read_objects(self):
        dataset_config = json.load(open('dataset_configs.json'))[self.dataset_name]
        train_object_dict, test_object_dict = self._load_object_dict_wrapper()
        partition_path = (f"{config.FilePaths.dataset_partition_path}"
                          f"{self.dataset_name}_seed{self.seed}.pkl")
        if not os.path.exists(partition_path):
            self.logger.info(f"Partition file missing — generating for seed {self.seed}...")
            import argparse
            from data_partition import DataPartitionGenerator
            partition_args = argparse.Namespace(
                dataset_name=self.dataset_name,
                train_neg_samples_list=[2, 5],
                train_size_ratio_list={"small": 0.1, "medium": 0.4, "large": 0.6},
                test_size_ratio_list={"small": 0.1, "medium": 0.5, "large": 1.0},
                test_negative_samples_list=[2, 5],
            )
            gen = DataPartitionGenerator(partition_args)
            gen.create_dataset_partition_dict(self.seed)
        data_partition_dict = load_dataset_partition_dict(self.dataset_name, self.logger, self.seed)
        if test_object_dict is not None and train_object_dict is not None:
            return data_partition_dict, train_object_dict, test_object_dict
        self.logger.info("Generating test object dict and train object dict")
        # Raw-object cache: produced by preprocess_hague.py (run once).
        # If missing, fall back to reading CityJSON files directly.
        # Each seed deepcopies before simulation so the cached version is never mutated.
        raw_cache_path = (f"{config.FilePaths.object_dict_path}"
                          f"{self.dataset_name}_raw.joblib")
        if os.path.exists(raw_cache_path):
            self.logger.info(f"Loading preprocessed cache: {raw_cache_path}")
            raw_object_dict = joblib.load(raw_cache_path)
            self.logger.info(
                f"  → {len(raw_object_dict['cands'])} cands, "
                f"{len(raw_object_dict['index'])} index buildings"
            )
        else:
            self.logger.info("No preprocessed cache found — running full read (slow).")
            raw_object_dict = getattr(self, f'_read_objects_{self.dataset_name}')(dataset_config)
            os.makedirs(os.path.dirname(raw_cache_path), exist_ok=True)
            joblib.dump(raw_object_dict, raw_cache_path, compress=3)
            self.logger.info(f"Raw object_dict cached to: {raw_cache_path}")
        # Optional: restrict to the first N shared grid cells for quick testing
        max_cells = config.Constants.max_grid_cells
        if max_cells is not None and 'grid_meta' in raw_object_dict:
            raw_object_dict = self._filter_to_grid_cells(raw_object_dict, max_cells)
        # Work on a fresh copy so the cached version is never modified by simulation
        object_dict = copy.deepcopy(raw_object_dict)
        # Apply disaster simulation to cands before property extraction.
        # load_object_dict must be False when disaster mode is active (cached dicts
        # are pre-simulation and would produce incorrect features).
        self._simulator = DisasterSimulator(config.DisasterSimulation, seed=self.seed)
        object_dict = self._simulator.apply(object_dict)
        train_object_dict, test_object_dict = self._partition_object_dict(object_dict, data_partition_dict)
        if config.Constants.save_object_dict:
            self._save_object_dicts(train_object_dict, test_object_dict, dataset_config)
        return data_partition_dict, train_object_dict, test_object_dict

    @staticmethod
    def _filter_to_grid_cells(raw_object_dict, max_cells):
        """
        Restrict both cands and index to buildings in the `max_cells` most-populated
        grid cells that are shared between both sources.
        Picking by population (not coordinate order) maximises pair coverage from the
        pre-built partition dict and ensures a spatially representative quick test.
        """
        from collections import Counter
        cands_cells = set(b['grid_cell'] for b in raw_object_dict['cands'].values())
        index_cells = set(b['grid_cell'] for b in raw_object_dict['index'].values())
        shared = cands_cells & index_cells
        # Sort shared cells by number of cands in descending order
        cell_pop = Counter(b['grid_cell'] for b in raw_object_dict['cands'].values())
        shared_cells = set(sorted(shared, key=lambda c: -cell_pop[c])[:max_cells])

        filtered = dict(raw_object_dict)  # shallow copy of top-level keys
        filtered['cands'] = {k: v for k, v in raw_object_dict['cands'].items()
                             if v['grid_cell'] in shared_cells}
        filtered['index'] = {k: v for k, v in raw_object_dict['index'].items()
                             if v['grid_cell'] in shared_cells}

        # Rebuild mapping dicts for filtered subset
        filtered['mapping_dict']     = {}
        filtered['inv_mapping_dict'] = {}
        for src in ('cands', 'index'):
            keys = sorted(filtered[src].keys())
            filtered['mapping_dict'][src]     = {i: k for i, k in enumerate(keys)}
            filtered['inv_mapping_dict'][src] = {k: i for i, k in enumerate(keys)}

        import logging
        logging.getLogger(__name__).info(
            f"[grid filter] {max_cells} shared cells → "
            f"{len(filtered['cands'])} cands, {len(filtered['index'])} index buildings"
        )
        return filtered

    def _load_object_dict_wrapper(self):
        test_object_dict, train_object_dict = None, None
        train_full_path, test_full_path = self._get_object_dict_paths()
        if config.Constants.load_object_dict:
            train_object_dict = load_object_dict(self.logger, train_full_path, 'train_object_dict')
            test_object_dict = load_object_dict(self.logger, test_full_path, 'test_object_dict')
        return train_object_dict, test_object_dict

    def _save_object_dicts(self, train_object_dict, test_object_dict, dataset_config):
        self._print_object_dict_stats(train_object_dict, test_object_dict)
        self.logger.info(f"Saving test object dict")
        train_full_path, test_full_path = self._get_object_dict_paths()
        self.logger.info(f"Saving train object dict to {train_full_path}")
        joblib.dump(train_object_dict, train_full_path)
        self.logger.info(f"Saving test object dict to {test_full_path}")
        joblib.dump(test_object_dict, test_full_path)
        return

    @staticmethod
    def _print_object_dict_stats(train_object_dict, test_object_dict):
        print(f"Number of cands in train: {len(train_object_dict['cands'])}")
        print(f"Number of index in train: {len(train_object_dict['index'])}")
        print(f"Number of cands in test: {len(test_object_dict['cands'])}")
        print(f"Number of index in test: {len(test_object_dict['index'])}")

    def _get_object_dict_paths(self):
        object_dict_path = f"{config.FilePaths.object_dict_path}{self.dataset_name}/"
        if not os.path.exists(object_dict_path):
            os.makedirs(object_dict_path)
        if self.evaluation_mode == 'blocking':
            train_full_path = f"{object_dict_path}train_blocking_{self.dataset_size_version}"
            test_full_path = f"{object_dict_path}test_blocking_{self.dataset_size_version}"
        else:
            train_full_path = (f"{object_dict_path}train_matching_{self.dataset_size_version}_"
                               f"neg_samples_num={self.neg_samples_num}")
            test_full_path = f"{object_dict_path}test_matching_{self.matching_cands_generation}" \
                             f"_{self.dataset_size_version}_neg_samples_num={self.neg_samples_num}"
        return f"{train_full_path}_seed_{self.seed}.joblib", f"{test_full_path}_seed_{self.seed}.joblib"

    def _partition_object_dict(self, object_dict, data_partition_dict):
        if self.evaluation_mode == "blocking":
            return self._clean_object_dict_blocking(object_dict, data_partition_dict)
        else:
            return self._clean_object_dict_matching(object_dict, data_partition_dict)

    def _clean_object_dict_blocking(self, object_dict, data_partition_dict):
        dataset_version = self.dataset_size_version
        train_object_dict = {'cands': {}, 'index': {}}
        test_object_dict = {'cands': {}, 'index': {}}
        avail_cands = set(object_dict['cands'].keys())
        avail_index = set(object_dict['index'].keys())
        train_pairs = data_partition_dict['train']['negative_sampling'][dataset_version][2]
        train_pairs = [p for p in train_pairs if p[0] in avail_cands and p[1] in avail_index]
        test_data_partition = data_partition_dict['test']['blocking'][dataset_version]
        test_cands_ids = [i for i in test_data_partition['cands'] if i in avail_cands]
        test_index_ids = [i for i in test_data_partition['index'] if i in avail_index]
        train_object_dict['cands'] = {pair[0]: object_dict['cands'][pair[0]] for pair in train_pairs}
        train_object_dict['index'] = {pair[1]: object_dict['index'][pair[1]] for pair in train_pairs}
        test_object_dict['cands'] = {object_id: object_dict['cands'][object_id] for object_id in test_cands_ids}
        test_object_dict['index'] = {object_id: object_dict['index'][object_id] for object_id in test_index_ids}
        return train_object_dict, test_object_dict

    def _clean_object_dict_matching(self, object_dict, data_partition_dict):
        train_object_dict = {'cands': {}, 'index': {}}
        test_object_dict = {'cands': {}, 'index': {}}
        dataset_version = self.dataset_size_version
        neg_num = self.neg_samples_num
        candidates_generation = self.matching_cands_generation
        train_pairs = data_partition_dict['train'][self.matching_cands_generation][dataset_version][neg_num]
        test_pairs = data_partition_dict['test']['matching'][candidates_generation][dataset_version][neg_num]
        # Filter pairs to IDs that exist in the loaded object_dict (important for
        # quick-test runs where max_files_per_source limits coverage)
        avail_cands = set(object_dict['cands'].keys())
        avail_index = set(object_dict['index'].keys())
        train_pairs = [p for p in train_pairs if p[0] in avail_cands and p[1] in avail_index]
        test_pairs  = [p for p in test_pairs  if p[0] in avail_cands and p[1] in avail_index]
        self.logger.info(f"Filtered to {len(train_pairs)} train pairs, {len(test_pairs)} test pairs "
                         f"(available cands={len(avail_cands)}, index={len(avail_index)})")
        train_object_dict['cands'] = {pair[0]: object_dict['cands'][pair[0]] for pair in train_pairs}
        train_object_dict['index'] = {pair[1]: object_dict['index'][pair[1]] for pair in train_pairs}
        test_object_dict['cands'] = {pair[0]: object_dict['cands'][pair[0]] for pair in test_pairs}
        test_object_dict['index'] = {pair[1]: object_dict['index'][pair[1]] for pair in test_pairs}
        return train_object_dict, test_object_dict

    @staticmethod
    def _remove_train_objects_from_object_dict(object_dict, train_ids):
        for objects_type in object_dict.keys():
            object_dict[objects_type] = {
                object_id: object_data
                for object_id, object_data in object_dict[objects_type].items()
                if object_id not in train_ids
            }
        return object_dict

    @staticmethod
    def _compute_object_centroid(vertices):
        unique_vertices = np.array(vertices)
        return unique_vertices.mean(axis=0)

    @staticmethod
    def _get_vertices(polygon_mesh):
        return np.unique(np.array([coord for surface in polygon_mesh for coord in surface]), axis=0)

    @staticmethod
    def _get_polygon_mesh(data, obj_key, vertices, min_surfaces_num):
        boundaries = data['CityObjects'][obj_key]['geometry'][0]['boundaries'][0]
        if len(boundaries) < min_surfaces_num:
            return None
        polygon_mesh = []
        for surface in boundaries:
            polygon_mesh.append([vertices[i] for sub_surface_list in surface for i in sub_surface_list])
        vertices = PipelineManager._get_vertices(polygon_mesh)
        centroid = PipelineManager._compute_object_centroid(vertices)
        return {'polygon_mesh': polygon_mesh, 'vertices': vertices, 'centroid': centroid}

    def _insert_polygon_mesh(self, object_dict, obj_type, obj_data, obj_ind, min_surfaces_num=10):
        vertices = obj_data['vertices']
        obj_key = list(obj_data['CityObjects'].keys())[0]
        polygon_mesh = self._get_polygon_mesh(obj_data, obj_key, vertices, min_surfaces_num)
        if polygon_mesh is not None:
            object_dict[obj_type][obj_ind] = polygon_mesh
        return object_dict

    def _read_objects_bo_em(self, dataset_config):
        objects_path_dict = read_object_path_dict(dataset_config)
        object_dict = defaultdict(dict)
        for objects_type, objects_path in objects_path_dict.items():
            file_list = [f for f in os.listdir(objects_path) if f.endswith('.json')]
            for filename in file_list:
                file_ind = int(filename.split('.')[0])
                json_data = read_json(objects_path, file_ind)
                object_dict = self._insert_polygon_mesh(object_dict, objects_type, json_data, file_ind)
            object_dict[objects_type] = dict(sorted(object_dict[objects_type].items()))
        return object_dict

    def _read_objects_gpkg(self, dataset_config):
        objects_path_dict = read_object_path_dict(dataset_config)
        object_dict = defaultdict(dict)
        for objects_type, objects_path in objects_path_dict.items():
            file_list = [f for f in os.listdir(objects_path) if f.endswith('.json')]
            for filename in file_list:
                file_ind = int(filename.split('.')[0])
                json_data = read_json(objects_path, file_ind)
                json_data = json.loads(json_data)
                object_dict = self._insert_polygon_mesh(object_dict, objects_type, json_data, file_ind)
            object_dict[objects_type] = dict(sorted(object_dict[objects_type].items()))
        return object_dict

    def _read_objects_delivery3(self, dataset_config):
        objects_path_dict = read_object_path_dict(dataset_config)
        object_dict = defaultdict(dict)
        mapping_dict = defaultdict(dict)
        inv_mapping_dict = defaultdict(dict)
        for objects_type, objects_path in objects_path_dict.items():
            file_list = [f for f in os.listdir(objects_path) if f.endswith('.json')]
            for file_ind, file_name in enumerate(file_list):
                file_name = file_name.split('.')[0]
                json_data = read_json(objects_path, file_name)
                object_dict = self._insert_polygon_mesh(object_dict, objects_type, json_data, file_ind)
                mapping_dict[objects_type][file_ind] = file_name
                inv_mapping_dict[objects_type][file_name] = file_ind
            object_dict[objects_type] = dict(sorted(object_dict[objects_type].items()))
        object_dict['mapping_dict'] = mapping_dict
        object_dict['inv_mapping_dict'] = inv_mapping_dict
        return object_dict

    def _read_objects_Hague(self, dataset_config):
        """
        Fallback reader used only when preprocess_hague.py has not been run.
        Prefer running `python preprocess_hague.py` once to create the cache.
        """
        from preprocess_hague import preprocess
        raw_cache_path = f"{config.FilePaths.object_dict_path}{self.dataset_name}_raw.joblib"
        self.logger.info("Running preprocess_hague.preprocess() to build cache...")
        return preprocess(
            cands_path=dataset_config['cands_path'],
            index_path=dataset_config['index_path'],
            output_path=raw_cache_path,
            cell_size=config.DataPartition.grid_cell_size,
            min_surfaces=self.min_surfaces_num,
        )

    def _generate_object_dict_mappings(self, object_dict, objects_path_dict):
        object_dict['mapping_dict'], object_dict['inv_mapping_dict'] = {}, {}
        for object_type in objects_path_dict:
            keys = list(object_dict[object_type].keys())
            object_dict['mapping_dict'][object_type] = {i: k for i, k in enumerate(keys)}
            object_dict['inv_mapping_dict'][object_type] = {k: i for i, k in enumerate(keys)}
        return object_dict

    @staticmethod
    def _process_object_file(file_ind, file_path, object_type, min_surfaces_num):
        print(f"Processing file {file_ind}")
        with open(file_path, 'r') as f:
            data = json.load(f)
        vertices = data['vertices']
        partial_dict = {}
        for obj_key in data['CityObjects'].keys():
            try:
                new_obj_key = PipelineManager.standardize_obj_key(obj_key, object_type)
                polygon_mesh_data = PipelineManager._get_polygon_mesh(data, obj_key, vertices,
                                                                      min_surfaces_num=min_surfaces_num)
                if polygon_mesh_data is not None:
                    partial_dict[new_obj_key] = polygon_mesh_data
            except:
                continue
        return partial_dict

    @staticmethod
    def standardize_obj_key(obj_key, object_type):
        if object_type == 'cands':
            return obj_key.split('bag_')[1]
        elif object_type == 'index':
            return obj_key.split('NL.IMBAG.Pand.')[1].split('-0')[0]
        else:
            raise ValueError('Invalid source')

    @staticmethod
    def read_objects_synthetic(self, dataset_config):
        pass

    # def _generate_training_pairs(self):
    #     np.random.seed(self.seed)
    #     index_ids = list(self.train_object_dict['index'].keys())
    #     pos_pairs = [(obj_id, obj_id) for obj_id in self.train_object_dict['cands'].keys()]
    #     neg_pairs = [(obj_id, np.random.choice(index_ids)) for obj_id in self.train_object_dict['cands'].keys()]
    #     neg_pairs = [(cand_id, index_id) for cand_id, index_id in neg_pairs if cand_id != index_id]
    #     return pos_pairs, neg_pairs

    # def _run_blocker(self):
    #     self.logger.info(f"Running blocking for training phase")
    #     dummy_feature_importance_scores = self._get_dummy_feature_importance_scores()
    #     dummy_property_ratios = self._get_dummy_property_ratios()
    #     blocker = Blocker(self.dataset_name, self.train_object_dict, self.train_property_dict,
    #                       dummy_feature_importance_scores, dummy_property_ratios, 'bkafi', 'train')
    #     self.logger.info(f"The blocking process for the training phase ended successfully")
    #     self.train_pos_pairs_dict, self.train_neg_pairs_dict = blocker.pos_pairs_dict, blocker.neg_pairs_dict
    #     save_blocking_output(self.train_pos_pairs_dict, self.train_neg_pairs_dict, self.seed, self.logger, 'train')
    #     return

    @staticmethod
    def _get_dummy_feature_importance_scores():
        feature_names = get_feature_name_list(config.Features.operator)
        dummy_model_name = config.Models.blocking_model
        return {dummy_model_name: [(feature, 1) for feature in feature_names]}

    def _get_dummy_property_ratios(self):
        property_ratios = {prop: {'mean': 1.0, 'std': 0.0}
                           for prop in self.train_property_dict.keys()}
        return property_ratios

    def _run_blocker(self, feature_importance_dict, train_property_ratios):
        blocking_method = self.blocking_method
        self.logger.info(f"Running blocking method {blocking_method}")
        blocker = Blocker(self.dataset_name, self.test_object_dict, self.test_property_dict, feature_importance_dict,
                          train_property_ratios,  self.blocking_method, self.sdr_factor, self.bkafi_criterion, 'test')
        self.logger.info(f"The blocking process ended successfully")
        self._save_blocking_output(blocker.pos_pairs_dict, blocker.neg_pairs_dict, blocker.blocking_execution_time)
        self.blocking_result_dict = self._evaluate_blocking(blocker.pos_pairs_dict, blocker.blocking_execution_time)
        return

    def _run_blocker_train(self, feature_importance_dict, train_property_ratios):
        blocking_method = self.blocking_method
        self.logger.info(f"Running blocking method {blocking_method} for train set")
        blocker = Blocker(self.dataset_name, self.train_object_dict, self.train_property_dict, feature_importance_dict,
                          train_property_ratios,  self.blocking_method, self.sdr_factor, self.bkafi_criterion, 'test')
        self.logger.info(f"The blocking process for train set ended successfully")
        pos_pairs_dict, neg_pairs_dict, execution_time = (blocker.pos_pairs_dict, blocker.neg_pairs_dict,
                                                          blocker.blocking_execution_time)
        self._save_blocking_output(pos_pairs_dict, neg_pairs_dict, execution_time, train_set_mode=True)
        return

    def _save_blocking_output(self, pos_pairs, neg_pairs, blocking_execution_time, train_set_mode=False):
        blocking_dict = {'pos_pairs': pos_pairs, 'neg_pairs': neg_pairs,
                         'blocking_execution_time': blocking_execution_time}
        blocking_output_path = self._get_blocking_output_path()
        if train_set_mode:
            blocking_output_path = blocking_output_path.replace('Operator', 'Train_Operator')
        try:
            joblib.dump(blocking_dict, blocking_output_path)
            message = f"Blocking results were saved successfully to {blocking_output_path}"
            self.logger.info(message)
        except Exception as e:
            self.logger.error(f"Error happened while saving blocking results: {e}")
        return

    def _get_blocking_output_path(self):
        file_name = get_file_name()
        blocking_results_path = config.FilePaths.results_path + 'blocking_output/'
        vector_normalization = 'True' if self.vector_normalization else 'False'
        sdr_factor = 'True' if self.sdr_factor else 'False'
        if not os.path.exists(blocking_results_path):
            os.makedirs(blocking_results_path)
        blocking_results_path = (f"{blocking_results_path}{file_name}_"
                                 f"{self.dataset_size_version}_neg_samples_num{self.neg_samples_num}"
                                 f"_vector_normalization_{vector_normalization}_sdr_factor_{sdr_factor}_"
                                 f"bkafi_criterion={self.bkafi_criterion}_seed={self.seed}.joblib")
        return blocking_results_path


    # def _get_property_dict_path(self, train_or_test):
    #     file_name = get_file_name_property_dict()
    #     property_dict_path = config.FilePaths.property_dict_path
    #     vector_normalization = self.vector_normalization if self.vector_normalization is not None else 'None'
    #     if not os.path.exists(property_dict_path):
    #         os.makedirs(property_dict_path)
    #     property_dict_path = (f"{property_dict_path}{file_name}_{train_or_test}_{self.evaluation_mode}_"
    #                           f"{self.dataset_size_version}_neg_samples_num={self.neg_samples_num}_"
    #                           f"vector_normalization={vector_normalization}_seed={self.seed}.joblib")
    #     return property_dict_path

    # def _save_blocking_evaluation(self, blocking_evaluation_dict, blocking_method_arg=None):
    #     file_name = get_file_name(blocking_method_arg)
    #     blocking_results_path = config.FilePaths.results_path
    #     vector_normalization = config.Features.normalization
    #     vector_normalization_str = vector_normalization if vector_normalization is not None else "None"
    #     sdr_factor = config.Blocking.sdr_factor
    #     sdr_factor_str = "True" if sdr_factor else "False"
    #     bkafi_criterion = config.Blocking.bkafi_criterion
    #     if not os.path.exists(blocking_results_path):
    #         os.makedirs(blocking_results_path)
    #     try:
    #         blocking_results_path = (f"{blocking_results_path}blocking_evaluation_results_{file_name}_"
    #                                  f"{self.dataset_size_version}_neg_samples_num{self.neg_samples_num}_"
    #                                  f"vector_normalization={vector_normalization_str}_sdr_factor_{sdr_factor_str}_"
    #                                  f"bkafi_criterion={bkafi_criterion}_seed={self.seed}.joblib")
    #         joblib.dump(blocking_evaluation_dict, blocking_results_path)
    #         self.logger.info(f"Blocking evaluation results were saved successfully")
    #     except Exception as e:
    #         self.logger.error(f"Error happened while saving blocking evaluation results: {e}")

    def _evaluate_blocking(self, pos_pairs_dict, blocking_execution_time):
        index_ids = set(self.test_object_dict['index'].keys())
        cand_ids = set(self.test_object_dict['cands'].keys())
        max_intersection = index_ids.intersection(cand_ids)
        if 'bkafi' in self.blocking_method:
            blocking_res_dict = self._evaluate_bkafi_blocking(max_intersection, pos_pairs_dict, blocking_execution_time)
        else:
            blocking_res_dict = self._evaluate_not_bkafi_blocking(max_intersection, pos_pairs_dict,
                                                                  blocking_execution_time)
        # self._save_blocking_evaluation(blocking_res_dict)
        return blocking_res_dict

    def _evaluate_bkafi_blocking(self, max_intersection, pos_pairs_dict, blocking_execution_time):
        blocking_res_dict = defaultdict(dict)
        for bkafi_dim in pos_pairs_dict.keys():
            for cand_pairs_per_item in pos_pairs_dict[bkafi_dim].keys():
                pos_pairs = set(pos_pairs_dict[bkafi_dim][cand_pairs_per_item])
                blocking_recall = round(len(pos_pairs) / len(max_intersection), 3)
                blocking_res_dict[bkafi_dim][cand_pairs_per_item] = {'blocking_recall': blocking_recall,
                                                                     'blocking_execution_time':
                                                                         blocking_execution_time[bkafi_dim]}
                if cand_pairs_per_item == 10:
                    self.logger.info(f"Blocking recall for {self.blocking_method}_dim {bkafi_dim} and "
                                     f"cand_pairs_per_item {cand_pairs_per_item}: {blocking_recall}")
                    self.logger.info(3*'- - - - - - - - - - - - -')
        return blocking_res_dict

    def _evaluate_not_bkafi_blocking(self, max_intersection, pos_pairs_dict, blocking_execution_time):
        blocking_res_dict = defaultdict(dict)
        for cand_pairs_per_item in pos_pairs_dict.keys():
            pos_pairs = set(pos_pairs_dict[cand_pairs_per_item])
            blocking_recall = round(len(pos_pairs) / len(max_intersection), 3)
            blocking_res_dict[cand_pairs_per_item] = {'blocking_recall': blocking_recall,
                                                      'blocking_execution_time': blocking_execution_time}
            # self.logger.info(f"Blocking recall for {self.blocking_method}, cand_pairs_per_item "
            #                  f"{cand_pairs_per_item}: {blocking_recall}")
            # self.logger.info(3*'--------------------------')
        return blocking_res_dict

    def _create_dataset_dict(self):
        dataset_dict = self._load_dataset_dict_wrapper()
        if dataset_dict is not None:
            return dataset_dict
        data_partition_dict, self.train_object_dict, self.test_object_dict = self._read_objects()
        self.train_pos_pairs, self.train_neg_pairs = self._extract_pairs(data_partition_dict, 'train')
        self.train_property_dict = self._generate_property_dict('train')
        if self.evaluation_mode == "matching":
            self.test_pos_pairs, self.test_neg_pairs = self._extract_pairs(data_partition_dict, 'test')
        self.test_property_dict = self._generate_property_dict('test')
        feature_dict = self._generate_feature_dict()
        dataset_dict = self._create_final_dict(feature_dict)
        return dataset_dict

    def _extract_pairs(self, data_partition_dict, train_or_test):
        if self.evaluation_mode == "blocking":
            pair_list = data_partition_dict[train_or_test]['negative_sampling'][self.dataset_size_version] \
                [self.neg_samples_num]
        else:
            if train_or_test == 'train':
                pair_list = data_partition_dict[train_or_test][self.matching_cands_generation] \
                    [self.dataset_size_version][self.neg_samples_num]
            else:
                pair_list = data_partition_dict[train_or_test]['matching'][self.matching_cands_generation] \
                    [self.dataset_size_version][self.neg_samples_num]
        # Same filter as _clean_object_dict_matching: drop pairs whose IDs aren't in the
        # loaded object dict, so PairProcessor never sees IDs missing from property_dict.
        object_dict = self.train_object_dict if train_or_test == 'train' else self.test_object_dict
        avail_cands = set(object_dict['cands'].keys())
        avail_index = set(object_dict['index'].keys())
        before = len(pair_list)
        pair_list = [p for p in pair_list if p[0] in avail_cands and p[1] in avail_index]
        dropped = before - len(pair_list)
        if dropped:
            self.logger.info(f"_extract_pairs[{train_or_test}]: dropped {dropped}/{before} pairs "
                             f"with IDs not in object_dict (kept {len(pair_list)})")
        pos_pairs = [pair for pair in pair_list if pair[0] == pair[1]]
        neg_pairs = [pair for pair in pair_list if pair[0] != pair[1]]
        return pos_pairs, neg_pairs

    def _load_dataset_dict_wrapper(self):
        dataset_dict = None
        if config.Constants.load_dataset_dict:
            dataset_dict = self._load_dataset_dict()
            if dataset_dict is not None:
                return dataset_dict
        return dataset_dict

    # def _get_pos_and_neg_pairs_for_training(self):
    #     bkafi_dim = min(self.train_pos_pairs_dict.keys())
    #     cand_pairs_per_item = min(self.test_pos_pairs_dict[bkafi_dim].keys())
    #     pos_pairs = self.train_pos_pairs_dict[bkafi_dim][cand_pairs_per_item]
    #     neg_pairs = self.train_neg_pairs_dict[bkafi_dim][cand_pairs_per_item]
    #     return pos_pairs, neg_pairs

    # def _get_pos_and_neg_pairs(self, train_or_test):
    #     pos_pairs_dict = self.test_pos_pairs_dict if train_or_test == 'test' else self.train_pos_pairs_dict
    #     neg_pairs_dict = self.test_neg_pairs_dict if train_or_test == 'test' else self.train_neg_pairs_dict
    #     bkafi_dim = min(pos_pairs_dict.keys())
    #     cand_pairs_per_item = min(pos_pairs_dict[bkafi_dim].keys())
    #     pos_pairs = pos_pairs_dict[bkafi_dim][cand_pairs_per_item]
    #     neg_pairs = neg_pairs_dict[bkafi_dim][cand_pairs_per_item]
    #     return pos_pairs, neg_pairs

    def _load_train_items(self):
        feature_importance_dict, matching_pairs_property_ratios = None, None
        try:
            feature_importance_dict = load_feature_importance_dict(self.seed, self.logger)
            matching_pairs_property_ratios = load_property_ratios(self.seed, self.logger)
        except:
            self.logger.info("Could not load training phase items. Running training phase pipeline")
        return feature_importance_dict, matching_pairs_property_ratios

    def _generate_property_dict(self, train_or_test):
        rel_object_dict = self.train_object_dict if train_or_test == 'train' else self.test_object_dict
        if config.Constants.load_property_dict:
            property_dict = self._load_property_dict(train_or_test)
            if property_dict is not None:
                return property_dict
        self.logger.info(f"Generating {train_or_test} property dictionary")
        obj_property_processor = ObjectPropertiesProcessor(rel_object_dict, self.vector_normalization)
        property_dict = obj_property_processor.prop_vals_dict
        property_dict_generation_time = obj_property_processor.property_dict_generation_time
        self.logger.info(f"Property dictionary generation time: {property_dict_generation_time}\n")
        if config.Constants.save_property_dict:
            self._save_property_dict(property_dict, train_or_test)
        return property_dict

    def _save_property_dict(self, property_dict, train_or_test):
        try:
            property_dict_path = self._get_property_dict_path(train_or_test)
            joblib.dump(property_dict, property_dict_path)
            self.logger.info(f"{train_or_test}_property_dict was saved successfully")
            self.logger.info('')
        except Exception as e:
            self.logger.error(f"Error happened while saving {train_or_test}_property_dict: {e}")
        return

    def _load_property_dict(self, train_or_test):
        property_dict_path = self._get_property_dict_path(train_or_test)
        try:
            property_dict = joblib.load(property_dict_path)
            self.logger.info(f"{train_or_test}_property_dict was loaded successfully")
            return property_dict
        except Exception as e:
            self.logger.error(f"Error happened while loading {train_or_test}_property_dict: {e}")
            return None

    def _get_property_dict_path(self, train_or_test):
        file_name = get_file_name_property_dict()
        property_dict_path = config.FilePaths.property_dict_path
        vector_normalization = 'True' if self.vector_normalization else 'False'
        if not os.path.exists(property_dict_path):
            os.makedirs(property_dict_path)
        property_dict_path = (f"{property_dict_path}{file_name}_{train_or_test}_{self.evaluation_mode}_"
                              f"{self.dataset_size_version}_neg_samples_num={self.neg_samples_num}_"
                              f"vector_normalization={vector_normalization}_seed={self.seed}.joblib")
        return property_dict_path

    def _generate_feature_dict(self):
        feature_dict = {'train': {}, 'test': {}} if self.evaluation_mode == 'matching' else {'train': {}}
        for train_or_test in feature_dict.keys():
            pos_pairs, neg_pairs, property_dict = self._get_rel_pairs_and_property_dict(train_or_test)
            self.logger.info(f"Generating {train_or_test} feature vectors")
            for label, pairs_list in zip([0, 1], [neg_pairs, pos_pairs]):
                feature_dict[train_or_test][label] = PairProcessor(property_dict, pairs_list).feature_vec
        return feature_dict

    def _get_rel_pairs_and_property_dict(self, train_or_test):
        if train_or_test == 'train':
            pos_pairs, neg_pairs = self.train_pos_pairs, self.train_neg_pairs
            property_dict = self.train_property_dict
        else:
            pos_pairs, neg_pairs = self.test_pos_pairs, self.test_neg_pairs
            property_dict = self.test_property_dict
        return pos_pairs, neg_pairs, property_dict

    def _create_final_dict(self, feature_dict):
        np.random.seed(self.seed)
        dataset_dict = {'train': {}, 'test': {}} if self.evaluation_mode == 'matching' else {'train': {}}
        for train_or_test in dataset_dict.keys():
            merged_features, merged_labels = self._merge_features_and_labels(feature_dict, train_or_test)
            if train_or_test == 'test' and self.evaluation_mode == 'matching':
                # Store pair IDs alongside X/Y so alignment can map scores to building IDs
                merged_pairs = self.test_neg_pairs + self.test_pos_pairs
                dataset_dict = self._prepare_dataset(dataset_dict, train_or_test,
                                                     merged_features, merged_labels,
                                                     merged_pairs=merged_pairs)
            else:
                dataset_dict = self._prepare_dataset(dataset_dict, train_or_test,
                                                     merged_features, merged_labels)
        if config.Constants.save_dataset_dict:
            self._save_dataset_dict(dataset_dict)
        return dataset_dict

    def _save_dataset_dict(self, dataset_dict):
        dataset_dict_path = self._get_dataset_dict_path()
        saving_message = f"dataset_dict was saved successfully"
        error_message = f"Error happened while saving dataset_dict: "
        try:
            joblib.dump(dataset_dict, dataset_dict_path)
            self.logger.info(saving_message)
            self.logger.info('')
        except Exception as e:
            self.logger.error(f"{error_message}{e}")
        return

    def _load_dataset_dict(self):
        dataset_dict_path = self._get_dataset_dict_path()
        try:
            dataset_dict = joblib.load(dataset_dict_path)
            self.logger.info(f"dataset_dict was loaded successfully")
            return dataset_dict
        except Exception as e:
            self.logger.error(f"Error happened while loading dataset_dict: {e}")
            return None

    def _get_dataset_dict_path(self):
        dataset_dict_dir = config.FilePaths.dataset_dict_path
        file_name = get_file_name()
        if not os.path.exists(dataset_dict_dir):
            os.makedirs(dataset_dict_dir)
        dataset_dict_path = (f"{dataset_dict_dir}{file_name}_{self.evaluation_mode}_{self.dataset_size_version}_"
                             f"neg_samples={self.neg_samples_num}_seed={self.seed}.joblib")
        return dataset_dict_path

    def _merge_features_and_labels(self, feature_dict, train_or_test):
        neg_feature_vecs, pos_feature_vecs = feature_dict[train_or_test][0], feature_dict[train_or_test][1]
        merged_features = neg_feature_vecs + pos_feature_vecs
        merged_labels = [0] * len(neg_feature_vecs) + [1] * len(pos_feature_vecs)
        return merged_features, merged_labels

    @staticmethod
    def _prepare_dataset(dataset_dict, file_type, merged_features, merged_labels,
                         merged_pairs=None):
        """
        Shuffle features/labels (and optionally pair IDs) together and store in dataset_dict.

        merged_pairs : list of (cand_id, index_id), parallel to merged_features.
            When provided, dataset_dict[file_type]['pairs'] is stored in the same
            shuffled order as X/Y — required for mapping classifier scores back to
            building IDs in the alignment step.
        """
        if merged_pairs is not None:
            combined = list(zip(merged_features, merged_labels, merged_pairs))
            np.random.shuffle(combined)
            dataset_dict[file_type]['X'] = np.array([e[0] for e in combined])
            dataset_dict[file_type]['Y'] = np.array([e[1] for e in combined])
            dataset_dict[file_type]['pairs'] = [e[2] for e in combined]
        else:
            combined = list(zip(merged_features, merged_labels))
            np.random.shuffle(combined)
            dataset_dict[file_type]['X'] = np.array([e[0] for e in combined])
            dataset_dict[file_type]['Y'] = np.array([e[1] for e in combined])
        return dataset_dict

    def _train_and_evaluate(self, ):
        if self.evaluation_mode == 'blocking':
            feature_importance_dict, train_property_ratios = self._train_for_blocking()
            if self.run_blocker_train:
                self._run_blocker_train(feature_importance_dict, train_property_ratios)
            else:
                self._run_blocker(feature_importance_dict, train_property_ratios)
            flexible_classifier = None
        else:
            flexible_classifier = self._run_matching_pipeline()
            self._run_alignment(flexible_classifier)
        return flexible_classifier

    def _run_alignment(self, flexible_classifier_obj):
        """
        Stage 4: Estimate rigid 3D transform from high-confidence matches and
        re-score all test pairs combining geometric + spatial proximity.

        Requires:
          - evaluation_mode == 'matching'
          - dataset_dict['test']['pairs'] populated by _create_final_dict
          - config.Alignment.enabled == True
        """
        if not config.Alignment.enabled:
            return
        if flexible_classifier_obj is None:
            return
        test_split = self.dataset_dict.get('test', {})
        if 'pairs' not in test_split:
            self.logger.warning("[_run_alignment] No pair IDs in dataset_dict['test']. "
                                "Ensure load_dataset_dict=False so pairs are freshly built.")
            return

        # Pick the primary model for scoring
        model_name = config.Models.model_to_use
        if model_name not in flexible_classifier_obj.best_model_dict:
            model_name = next(iter(flexible_classifier_obj.best_model_dict))
        best_model = flexible_classifier_obj.best_model_dict[model_name]['model']

        X_test = test_split['X']
        pairs  = test_split['pairs']   # list of (cand_id, index_id), same shuffle order as X

        # Geometric scores: P(match=1)
        proba = best_model.predict_proba(X_test)
        match_class_idx = list(best_model.classes_).index(1)
        geo_scores = proba[:, match_class_idx]

        scored_pairs = [(cid, iid, float(s)) for (cid, iid), s in zip(pairs, geo_scores)]

        self.logger.info(
            f"[_run_alignment] {len(scored_pairs)} test pairs | "
            f"model={model_name} | "
            f"anchors with score>={config.Alignment.confidence_threshold}: "
            f"{sum(1 for _,_,s in scored_pairs if s >= config.Alignment.confidence_threshold)}"
        )

        aligner = RigidAligner(config.Alignment, logger=self.logger)
        ground_truth_R = getattr(self._simulator, 'R_crs', None)
        ground_truth_t = getattr(self._simulator, 't_crs', None)

        rescored_pairs = aligner.run(
            self.test_object_dict,
            scored_pairs,
            suffix=f"seed{self.seed}",
            ground_truth_R=ground_truth_R,
            ground_truth_t=ground_truth_t,
        )

        # Log final score improvement summary
        if aligner.alignment_succeeded:
            top_geo    = sorted(scored_pairs,   key=lambda x: x[2], reverse=True)[:10]
            top_final  = sorted(rescored_pairs, key=lambda x: x[2], reverse=True)[:10]
            self.logger.info(
                f"[_run_alignment] Top-10 mean geometric score: "
                f"{np.mean([s for _,_,s in top_geo]):.3f} → "
                f"final score: {np.mean([s for _,_,s in top_final]):.3f}"
            )

        # Precision / Recall / F1 before and after alignment
        self._log_alignment_metrics(scored_pairs, rescored_pairs, self.test_object_dict)

    def _log_alignment_metrics(self, scored_pairs, rescored_pairs, test_object_dict,
                               score_threshold=0.5, dist_thresholds=(10.0, 25.0, 50.0)):
        """
        Log two sets of metrics:

        1. Score-based (before alignment only) — classifier Precision/Recall/F1
           at score_threshold.  Measures how well the geometric features identify matches.

        2. Distance-based (after alignment) — for each matched candidate, check whether
           its aligned centroid is within dist_threshold meters of its true match centroid.
           This is the correct evaluation after alignment: if the transform is good,
           every candidate should be physically co-located with its match.

        Note: candidates with no true match in the index are never counted as false
        negatives — recall is only over the intersection (buildings with a real match).
        """
        # --- 1. Score-based metrics (before alignment) ---
        def _prf(pairs):
            tp = sum(1 for cid, iid, s in pairs if s >= score_threshold and cid == iid)
            fp = sum(1 for cid, iid, s in pairs if s >= score_threshold and cid != iid)
            fn = sum(1 for cid, iid, s in pairs if s <  score_threshold and cid == iid)
            precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
            recall    = tp / (tp + fn) if (tp + fn) > 0 else 0.0
            f1        = (2 * precision * recall / (precision + recall)
                         if (precision + recall) > 0 else 0.0)
            return round(precision, 3), round(recall, 3), round(f1, 3)

        pre_p, pre_r, pre_f1 = _prf(scored_pairs)
        self.logger.info(
            f"[Metrics] Before alignment (score≥{score_threshold}) — "
            f"Precision: {pre_p}  Recall: {pre_r}  F1: {pre_f1}"
        )

        # --- 2. Distance-based metrics (after alignment) ---
        # After alignment, test_object_dict['cands'] centroids are already transformed.
        # True matches are pairs where cand_id == index_id.
        cands  = test_object_dict.get('cands', {})
        index  = test_object_dict.get('index', {})
        # All matched cands (ground truth positives in the test set)
        matched_cands = {cid for cid, iid, _ in scored_pairs if cid == iid and cid in cands and iid in index}
        n_matched = len(matched_cands)

        if n_matched == 0:
            self.logger.warning("[Metrics] No matched pairs found for distance evaluation.")
            return

        # Compute distance from each aligned cand centroid to its true match index centroid
        distances = []
        for cid in matched_cands:
            c_centroid = np.asarray(cands[cid]['centroid'], dtype=np.float64)
            i_centroid = np.asarray(index[cid]['centroid'], dtype=np.float64)
            distances.append(np.linalg.norm(c_centroid - i_centroid))

        distances = np.array(distances)
        self.logger.info(
            f"[Metrics] After alignment (distance-based, n={n_matched} matched buildings) — "
            f"mean dist: {distances.mean():.1f} m  |  "
            f"median dist: {np.median(distances):.1f} m  |  "
            f"max dist: {distances.max():.1f} m"
        )
        for d_thresh in dist_thresholds:
            recall_d = round((distances < d_thresh).sum() / n_matched, 3)
            self.logger.info(
                f"[Metrics] After alignment  distance recall@{d_thresh:.0f}m: {recall_d} "
                f"({(distances < d_thresh).sum()}/{n_matched} buildings within {d_thresh:.0f} m of true match)"
            )

    def _train_for_blocking(self):
        self.logger.info("Training for blocking")
        if config.Constants.load_train_items:
            feature_importance_dict, matching_pairs_property_ratios = self._load_train_items()
            if feature_importance_dict is not None and matching_pairs_property_ratios is not None:
                return feature_importance_dict, matching_pairs_property_ratios
        params_dict = self._read_config_models()
        load_trained_models = config.Models.load_trained_models
        cv = config.Models.cv
        flexible_classifier_obj = FlexibleClassifier(self.dataset_dict, self.train_property_dict, params_dict,
                                                     self.seed, self.logger, self.dataset_name, 'blocking',
                                                     self.dataset_size_version, self.neg_samples_num,
                                                     load_trained_models, cv)
        feature_importance_dict = flexible_classifier_obj.feature_importance_extraction()
        train_property_ratios = flexible_classifier_obj.get_property_ratios()
        return feature_importance_dict, train_property_ratios

    def _run_matching_pipeline(self):
        self.logger.info("Training for matching")
        params_dict = self._read_config_models()
        load_trained_models = config.Models.load_trained_models
        cv = config.Models.cv
        flexible_classifier_obj = FlexibleClassifier(self.dataset_dict, None, params_dict, self.seed, self.logger,
                                                     self.dataset_name, 'matching', self.dataset_size_version,
                                                     self.neg_samples_num, load_trained_models, cv)
        return flexible_classifier_obj


    def _read_config_models(self):
        model_list = config.Models.model_list if self.evaluation_mode == 'matching' else [config.Models.blocking_model]
        params_dict = dict()
        for model in model_list:
            params_dict[model] = config.Models.params_dict[model]
        return params_dict

    def _get_result_dict(self):
        if self.evaluation_mode == 'blocking':
            if self.run_blocker_train:
                return None
            return {'blocking': self.blocking_result_dict}
        elif self.evaluation_mode == 'matching':
            return {'matching': self.flexible_classifier_obj.result_dict}
        else:
            raise ValueError(f"Evaluation mode {self.evaluation_mode} is not supported")