STER / code /generate_partitions.py
eduzrh's picture
Upload code/generate_partitions.py with huggingface_hub
dc54818 verified
Raw
History Blame Contribute Delete
9.29 kB
#!/usr/bin/env python3
"""
Generate 3dSAGER-compatible partition files for all 18 STER cities.
For each city:
1. Downloads object_dict_raw.joblib
2. Splits buildings into train/test (80/20) respecting spatial distribution
3. Generates positive pairs (same building ID)
4. Generates negative pairs (random mismatches)
5. Saves {city}_seed{1,2,3}.pkl
Format matches 3dSAGER DataPartitionGenerator output:
{
'train': {
'negative_sampling': {
'small': {2: [(cand_idx, index_idx), ...], 5: [...]},
'large': {2: [...], 5: [...]}
}
},
'test': {
'matching': {
'negative_sampling': {...},
'blocking-based': {...}
},
'blocking': {
'small': {'cands': set(), 'index': set()},
'large': {'cands': set(), 'index': set()}
}
}
}
"""
import os, sys, pickle, argparse, logging
import numpy as np
from collections import defaultdict
from huggingface_hub import hf_hub_download, HfApi
logger = logging.getLogger("partition_gen")
logger.setLevel(logging.INFO)
h = logging.StreamHandler(sys.stdout)
h.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
logger.addHandler(h)
NEG_SAMPLE_COUNTS = [2, 5]
SEEDS = [1, 2, 3]
TRAIN_RATIO = 0.8
TEST_RATIO = 0.2
GRID_SIZE = 3 # 3x3 spatial grid
REPO = "eduzrh/STER"
def download_object_dict(city):
"""Download SIGMOD-format object_dict for a city."""
path = hf_hub_download(REPO, f"data/{city}/object_dict_raw.joblib", repo_type="dataset")
import joblib
return joblib.load(path)
def spatial_train_test_split(cand_ids, index_ids, od, test_ratio=0.2, grid_size=3, seed=42):
"""
Split buildings spatially using grid-based partitioning.
Returns (train_cand_ids, train_index_ids, test_cand_ids, test_index_ids).
"""
rng = np.random.RandomState(seed)
# Get centroids for spatial partitioning
centroids = {}
for bid in cand_ids:
rec = od['cands'].get(bid, {})
c = rec.get('centroid', np.zeros(3))
centroids[bid] = np.asarray(c)
if len(centroids) == 0:
return set(), set(), set(), set()
# Collect all centroids
pts = np.array([centroids[bid][:2] for bid in cand_ids if bid in centroids])
ids_arr = np.array([bid for bid in cand_ids if bid in centroids])
if len(pts) < 10:
# Too few buildings, random split
n = len(ids_arr)
n_test = max(1, int(n * test_ratio))
idx = rng.permutation(n)
test_ids = set(ids_arr[idx[:n_test]])
train_ids = set(ids_arr[idx[n_test:]])
return train_ids, train_ids, test_ids, test_ids
# Grid-based binning
x_min, y_min = pts.min(axis=0)
x_max, y_max = pts.max(axis=0)
x_bins = np.linspace(x_min, x_max, grid_size + 1)
y_bins = np.linspace(y_min, y_max, grid_size + 1)
x_idx = np.digitize(pts[:, 0], x_bins) - 1
y_idx = np.digitize(pts[:, 1], y_bins) - 1
x_idx = np.clip(x_idx, 0, grid_size - 1)
y_idx = np.clip(y_idx, 0, grid_size - 1)
cells = defaultdict(list)
for i, bid in enumerate(ids_arr):
cells[(x_idx[i], y_idx[i])].append(bid)
# Sample test buildings from each cell proportionally
test_ids = set()
train_ids = set()
for cell_ids in cells.values():
cell_ids = list(cell_ids)
n_cell_test = max(1, int(len(cell_ids) * test_ratio))
rng.shuffle(cell_ids)
test_ids.update(cell_ids[:n_cell_test])
train_ids.update(cell_ids[n_cell_test:])
return train_ids, train_ids, test_ids, test_ids
def generate_pairs(cand_ids, index_ids, inv_map_cands, inv_map_index, neg_count, rng, cand_map, index_map):
"""
Generate positive and negative pairs.
Positive: same building ID → (cand_idx, index_idx)
Negative: random mismatched buildings
"""
common = sorted(set(cand_ids) & set(index_ids))
pos_pairs = []
for bid in common:
ci = inv_map_cands.get(bid)
ii = inv_map_index.get(bid)
if ci is not None and ii is not None:
pos_pairs.append((ci, ii))
n_pos = len(pos_pairs)
neg_pairs = []
if n_pos > 0 and neg_count > 0:
# Shuffle cands to create mismatches
cand_idx_list = [inv_map_cands[bid] for bid in common if bid in inv_map_cands]
index_idx_list = [inv_map_index[bid] for bid in common if bid in inv_map_index]
for _ in range(neg_count * n_pos):
ci = rng.choice(cand_idx_list)
ii = rng.choice(index_idx_list)
# Ensure negative: different building ID
cand_bid = cand_map.get(ci, '')
index_bid = index_map.get(ii, '')
if cand_bid != index_bid:
neg_pairs.append((ci, ii))
if len(neg_pairs) >= neg_count * n_pos:
break
return pos_pairs, neg_pairs
def generate_partition(city, od, seed):
"""Generate a full partition dict for one city/seed."""
rng = np.random.RandomState(seed)
cand_ids = set(od['cands'].keys())
index_ids = set(od['index'].keys())
inv_map_cands = od['inv_mapping_dict']['cands']
inv_map_index = od['inv_mapping_dict']['index']
# Split into train/test
train_cand, train_idx, test_cand, test_idx = spatial_train_test_split(
list(cand_ids), list(index_ids), od, TEST_RATIO, GRID_SIZE, seed
)
common = sorted(cand_ids & index_ids)
n_total = len(common)
n_train = int(n_total * TRAIN_RATIO)
# 'large' = all buildings, 'small' = subset (~30%)
n_small = max(int(n_total * 0.3), 10)
# Build partition dict
part = {
'train': {'negative_sampling': {}},
'test': {
'matching': {'negative_sampling': {}, 'blocking-based': {}},
'blocking': {}
}
}
for size_name, subset_ids in [('small', set(sorted(common)[:n_small])),
('large', set(common))]:
for neg in NEG_SAMPLE_COUNTS:
pos, neg_pairs = generate_pairs(subset_ids, subset_ids, inv_map_cands, inv_map_index, neg, rng, od['mapping_dict']['cands'], od['mapping_dict']['index'])
part['train']['negative_sampling'].setdefault(size_name, {})[neg] = pos + neg_pairs
# Test matching
test_common = sorted(test_cand & test_idx)
for size_name, subset_ids in [('small', set(test_common[:max(1, len(test_common)//3)])),
('large', set(test_common))]:
for neg in NEG_SAMPLE_COUNTS:
pos, neg_pairs = generate_pairs(subset_ids, subset_ids, inv_map_cands, inv_map_index, neg, rng, od['mapping_dict']['cands'], od['mapping_dict']['index'])
part['test']['matching']['negative_sampling'].setdefault(size_name, {})[neg] = pos + neg_pairs
# blocking-based test pairs (all pos, no neg)
pos_all, _ = generate_pairs(subset_ids, subset_ids, inv_map_cands, inv_map_index, 0, rng, od['mapping_dict']['cands'], od['mapping_dict']['index'])
part['test']['matching']['blocking-based'][size_name] = {2: pos_all, 5: pos_all}
# Test blocking
for size_name, subset_ids in [('small', set(sorted(test_common)[:max(1, len(test_common)//3)])),
('large', set(test_common))]:
part['test']['blocking'][size_name] = {
'cands': {inv_map_cands[bid] for bid in subset_ids if bid in inv_map_cands},
'index': {inv_map_index[bid] for bid in subset_ids if bid in inv_map_index},
}
return part
def process_city(city, api):
"""Generate partitions for all seeds for one city."""
import joblib
logger.info(f"[{city}] Loading object_dict...")
try:
od = download_object_dict(city)
except Exception as e:
logger.error(f"[{city}] Download failed: {e}")
return False
logger.info(f"[{city}] {len(od['cands'])} buildings")
for seed in SEEDS:
fname = f"{city}_seed{seed}.pkl"
local = f"/root/autodl-tmp/{fname}"
logger.info(f"[{city}] Generating seed={seed}...")
part = generate_partition(city, od, seed)
with open(local, 'wb') as f:
pickle.dump(part, f)
mb = os.path.getsize(local) / 1e6
logger.info(f"[{city}] seed={seed}: {mb:.1f} MB, uploading...")
api.upload_file(
path_or_fileobj=local,
path_in_repo=f"data/{city}/{fname}",
repo_id=REPO,
repo_type="dataset"
)
os.unlink(local)
return True
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument('--city', type=str, default=None)
args = ap.parse_args()
api = HfApi()
CITIES = [
"amsterdam","rotterdam","hague","utrecht","eindhoven","groningen","maastricht",
"chiyoda","shinjuku","setagaya","chuo","ota","minato","bunkyo","koto",
"kyoto","osaka","sakai"
]
if args.city:
CITIES = [args.city]
for city in CITIES:
try:
process_city(city, api)
except Exception as e:
logger.error(f"[{city}] FAILED: {e}", exc_info=True)
logger.info("=== ALL DONE ===")