import os from pathlib import Path import shutil import random from datetime import datetime try: import rasterio from rasterio.windows import from_bounds except ImportError: raise ImportError("This script requires rasterio. Install it with: pip install rasterio") areas = {'ATA_MV', 'BRA_SP', 'CHN_WS', 'ESP_EH', 'FIN_LM', 'GER_BN', 'IDN_SV', 'KAZ_AC', 'KSA_WA', 'NAM_HF', 'NZL_KP', 'PHL_TA', 'USA_GC'} data_path = Path("/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data/") tiny_path = Path("/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1-tiny/data/") # Configuration SEED = 42 N = 5 # <-- n x n tiles contiguous subset TILE_SIZE = 333 # Expected tile dimension in pixels INCLUDE_ANNOTATIONS = True random.seed(SEED) def build_tile_grid(tiles_src): """ Reads all tiles and builds a 2D grid based on their top-left geographic corners. Returns (grid, n_rows, n_cols) where grid[r][c] is a Path or None. """ tile_info = [] for tile_path in tiles_src.iterdir(): if tile_path.suffix != '.tif': continue try: with rasterio.open(tile_path) as src: if src.width != TILE_SIZE or src.height != TILE_SIZE: print(f" ⚠️ {tile_path.name} is {src.width}x{src.height}, " f"expected {TILE_SIZE}x{TILE_SIZE}") # Top-left corner in geo coordinates x, y = src.transform * (0, 0) tile_info.append((y, x, tile_path)) except Exception as e: print(f" ⚠️ Error reading {tile_path.name}: {e}") continue if not tile_info: return None, 0, 0 # Pixel size from first tile to set clustering tolerance with rasterio.open(tile_info[0][2]) as src: pixel_size = max(abs(src.transform.a), abs(src.transform.e)) # Tolerance: half the expected geo-distance between adjacent tile origins tol = TILE_SIZE * pixel_size * 0.5 ys = [t[0] for t in tile_info] xs = [t[1] for t in tile_info] # Unique Y coordinates = rows (top to bottom, descending) unique_ys = [] for y in sorted(ys, reverse=True): if not unique_ys or abs(y - unique_ys[-1]) > tol: unique_ys.append(y) # Unique X coordinates = columns (left to right, ascending) unique_xs = [] for x in sorted(xs): if not unique_xs or abs(x - unique_xs[-1]) > tol: unique_xs.append(x) n_rows = len(unique_ys) n_cols = len(unique_xs) # Place each tile in the grid grid = [[None for _ in range(n_cols)] for _ in range(n_rows)] for y, x, path in tile_info: row_idx = min(range(n_rows), key=lambda i: abs(y - unique_ys[i])) col_idx = min(range(n_cols), key=lambda i: abs(x - unique_xs[i])) grid[row_idx][col_idx] = path return grid, n_rows, n_cols # ------------------------------------------------------------------ print("=" * 80) print("MatchGeo-DEM Tiny Dataset Generator — n×n Tile Subset") print(f"Subset size: {N}x{N} tiles ({N*TILE_SIZE}x{N*TILE_SIZE} pixels)") print(f"Output: {tiny_path}") print("=" * 80) total_copied = 0 total_size = 0 for location in sorted(areas): src_dir = data_path / location dst_dir = tiny_path / location if not src_dir.exists(): print(f"\n⚠️ {location}: Source not found, skipping") continue dst_dir.mkdir(parents=True, exist_ok=True) print(f"\n📁 {location}:") # ------------------------------------------------------------------ # 1. Build tile grid and select random n×n window # ------------------------------------------------------------------ tiles_src = src_dir / "tiles" if not tiles_src.exists(): print(f" ⚠️ Tiles directory not found, skipping") continue grid, n_rows, n_cols = build_tile_grid(tiles_src) if grid is None: print(f" ⚠️ No valid tiles found, skipping") continue print(f" 📐 Grid: {n_rows} rows × {n_cols} cols") # Clamp window to actual grid size win_h = min(N, n_rows) win_w = min(N, n_cols) max_row = n_rows - win_h max_col = n_cols - win_w start_row = random.randint(0, max_row) if max_row > 0 else 0 start_col = random.randint(0, max_col) if max_col > 0 else 0 end_row = start_row + win_h end_col = start_col + win_w if win_h < N or win_w < N: print(f" ℹ️ Grid smaller than {N}x{N}; using {win_h}x{win_w} window") else: print(f" 🎯 Window: rows {start_row}-{end_row-1}, cols {start_col}-{end_col-1}") # Collect selected tiles selected_tiles = [] for r in range(start_row, end_row): for c in range(start_col, end_col): if grid[r][c] is not None: selected_tiles.append(grid[r][c]) if not selected_tiles: print(f" ⚠️ No tiles in selected window, skipping") continue # ------------------------------------------------------------------ # 2. Copy selected tiles # ------------------------------------------------------------------ tiles_dst = dst_dir / "tiles" tiles_dst.mkdir(parents=True, exist_ok=True) selected_names = set() for tile_path in selected_tiles: dst = tiles_dst / tile_path.name shutil.copy2(tile_path, dst) total_size += tile_path.stat().st_size selected_names.add(tile_path.stem) total_copied += len(selected_tiles) expected = win_h * win_w if len(selected_tiles) < expected: print(f" ✅ Tiles: {len(selected_tiles)}/{expected} copied (incomplete grid)") else: print(f" ✅ Tiles: {len(selected_tiles)}/{expected} copied") # ------------------------------------------------------------------ # 3. Crop merged DEM to the exact bounds of selected tiles # ------------------------------------------------------------------ merged_src = src_dir / f"{location}.tif" merged_dst = dst_dir / f"{location}.tif" if merged_src.exists(): # Union of selected tile bounds left = float('inf') bottom = float('inf') right = float('-inf') top = float('-inf') for tile_path in selected_tiles: with rasterio.open(tile_path) as src: b = src.bounds left = min(left, b.left) bottom = min(bottom, b.bottom) right = max(right, b.right) top = max(top, b.top) with rasterio.open(merged_src) as src: window = from_bounds(left, bottom, right, top, src.transform) window = window.round_lengths().round_offsets() profile = src.profile.copy() profile.update({ 'height': int(window.height), 'width': int(window.width), 'transform': src.window_transform(window) }) with rasterio.open(merged_dst, 'w', **profile) as dst: dst.write(src.read(window=window)) size = merged_dst.stat().st_size total_size += size print(f" ✅ Cropped DEM: {size/1024/1024:.1f} MB " f"({int(window.width)}x{int(window.height)} px)") else: print(f" ⚠️ Merged DEM not found") # ------------------------------------------------------------------ # 4. Copy metadata (omit geojsons that no longer describe the subset) # ------------------------------------------------------------------ for meta_file in [f"{location}_metadata.json", f"{location}.qmd"]: src = src_dir / meta_file dst = dst_dir / meta_file if src.exists(): shutil.copy2(src, dst) print(f" ✅ Metadata copied (extent/tiles geojsons omitted)") # ------------------------------------------------------------------ # 5. Copy annotations for selected tiles only # ------------------------------------------------------------------ anno_src = src_dir / "annotations" anno_dst = dst_dir / "annotations" if INCLUDE_ANNOTATIONS and anno_src.exists(): anno_dst.mkdir(parents=True, exist_ok=True) copied_anno = 0 for anno_file in anno_src.iterdir(): if anno_file.suffix == '.json' and anno_file.stem in selected_names: dst = anno_dst / anno_file.name shutil.copy2(anno_file, dst) copied_anno += 1 print(f" ✅ Annotations: {copied_anno} copied") # ------------------------------------------------------------------ # Summary # ------------------------------------------------------------------ total_mb = total_size / (1024 * 1024) total_gb = total_size / (1024 * 1024 * 1024) print(f"\n{'='*80}") print(f"📊 TINY DATASET SUMMARY:") print(f" Subset size: up to {N}x{N} tiles ({N*TILE_SIZE}x{N*TILE_SIZE} pixels)") print(f" Total tiles copied: {total_copied}") print(f" Total size: {total_mb:.1f} MB ({total_gb:.2f} GB)") print(f" Output path: {tiny_path}") print(f"{'='*80}") # Create README tiny_readme = tiny_path.parent / "README.txt" with open(tiny_readme, 'w') as f: f.write(f"""MatchGeo-DEM Tiny Dataset ========================= This is a SPATIAL SUBSET of the full MatchGeo-DEM dataset. Each city was cropped to a random contiguous {N}x{N} tile window. Each tile is {TILE_SIZE}x{TILE_SIZE} pixels. Total subset size per city: up to {N*TILE_SIZE}x{N*TILE_SIZE} pixels. Configuration: - Tiles per city: up to {N}x{N} = {N*N} tiles - Tile size: {TILE_SIZE}x{TILE_SIZE} pixels - Random seed: {SEED} - Total tiles: {total_copied} - Total size: {total_mb:.1f} MB NOTE: The original _extent.geojson and _tiles.geojson files were omitted because they no longer describe the cropped subset. Regenerate them from the cropped DEM if your pipeline requires them. For the full dataset, see: https://doi.org/10.5281/zenodo.19339008 Last generated: {datetime.now().strftime('%Y-%m-%d')} """) print(f"\n✅ Tiny README saved to: {tiny_readme}")