""" STER — Cross-LoD & Zero-shot difficulty map (run after the multi-LoD crawl). Uses the official ObjectPropertiesProcessor to compute the same 25 properties for each (building, LoD), then builds two HARD tasks the clean Hague benchmark can't: TASK A Cross-LoD matching: candidate = LoD1.2 (coarse block) , index = LoD2.2 (detailed roof) positive = same BAG id ; negative = different id (blocking-style top-k) -> baseline F1 expected << 0.95 (large geometric gap = genuine 'noisy' regime) TASK B Zero-shot transfer: train a matcher on 3DBAG multi-LoD pairs (LoD1.2<->LoD2.2), test on the Hague cross-source task (cand<->index) with NO target labels -> measures whether transformation-consistency transfers across sources. Outputs experiments/crosslod/crosslod_zeroshot.json """ import os, sys, json, warnings, numpy as np, joblib warnings.filterwarnings("ignore") sys.path.insert(0, ".") import config config.Features.normalization = 'log_transform' from object_properties import ObjectPropertiesProcessor from sklearn.ensemble import BaggingClassifier from sklearn.metrics import f1_score, precision_score, recall_score ML_DIR = "../../data/3dbag_multilod" PROPS = config.Features.object_properties MAX_RATIO = config.Constants.max_ratio_val SEED = 1 rng = np.random.RandomState(SEED) if not os.path.exists(os.path.join(ML_DIR, "3dbag_lod22.joblib")): print("multi-LoD data not present yet:", ML_DIR); sys.exit(0) lod12 = joblib.load(os.path.join(ML_DIR, "3dbag_lod12.joblib")) lod22 = joblib.load(os.path.join(ML_DIR, "3dbag_lod22.joblib")) common = sorted(set(lod12) & set(lod22)) print(f"multi-LoD buildings: lod12={len(lod12)} lod22={len(lod22)} common={len(common)}", flush=True) def props_for(object_dict): """Compute the 25 log-normalised properties -> {prop:{'cands':{id:v},'index':{id:v}}}.""" p = ObjectPropertiesProcessor(object_dict, vector_normalization=True) return p.prop_vals_dict def ratio_feat(pd, c, i, cand_side='cands', idx_side='index'): row = [] for p in PROPS: try: cv, iv = pd[p][cand_side][c], pd[p][idx_side][i] row.append(min(MAX_RATIO, round(cv / iv, 3)) if iv != 0 else MAX_RATIO) except (KeyError, ZeroDivisionError): row.append(0.0) return row def build_pairs(ids_cand, ids_idx, k_neg=2): """positive: (id,id); negatives: k_neg random different-id index buildings.""" pairs, labels = [], [] idx_pool = list(ids_idx) for c in ids_cand: if c in ids_idx: pairs.append((c, c)); labels.append(1) negs = rng.choice(idx_pool, size=min(k_neg, len(idx_pool)), replace=False) for n in negs: if n != c: pairs.append((c, n)); labels.append(0) return pairs, np.array(labels) # ---- TASK A: cross-LoD matching (lod12 = cands, lod22 = index) ---- print("\n[TASK A] Cross-LoD matching (LoD1.2 -> LoD2.2)", flush=True) od = {'cands': {k: lod12[k] for k in common}, 'index': {k: lod22[k] for k in common}} pd_cl = props_for(od) pairs, y = build_pairs(common, set(common), k_neg=2) X = np.array([ratio_feat(pd_cl, c, i) for c, i in pairs]) # train/test split by building id tr_ids = set(rng.choice(common, int(0.6 * len(common)), replace=False)) tr = np.array([1 if p[0] in tr_ids else 0 for p in pairs], dtype=bool) clf = BaggingClassifier(n_estimators=50, random_state=SEED).fit(X[tr], y[tr]) pred = clf.predict(X[~tr]) taskA = dict(n_pairs=len(pairs), n_pos=int(y.sum()), precision=round(precision_score(y[~tr], pred, zero_division=0), 4), recall=round(recall_score(y[~tr], pred, zero_division=0), 4), f1=round(f1_score(y[~tr], pred, zero_division=0), 4)) print(" ", taskA, flush=True) report = {"n_common": len(common), "task_A_cross_lod": taskA} os.makedirs("../../experiments/crosslod", exist_ok=True) with open("../../experiments/crosslod/crosslod_zeroshot.json", "w") as f: json.dump(report, f, indent=2) print("\nSaved -> experiments/crosslod/crosslod_zeroshot.json", flush=True) print("NOTE: Task B (zero-shot transfer to Hague) added once Hague props are aligned.", flush=True)