File size: 4,456 Bytes
02add7a | 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 | """Convert per-basin EU-Hydro GeoPackages into curated GeoParquet shards.
For each `euhydro_*_v013_GPKG.zip` in the current directory: extract the
package to a temp dir once, pull the layers that matter for water analysis,
drop Z/M dimensions and admin-only columns, write one GeoParquet per basin
per layer under `eu_hydro_master_skeleton_geoparquet/<layer_dir>/`, and
delete the extracted temp dir.
"""
from __future__ import annotations
import glob
import shutil
import sys
import tempfile
import time
import zipfile
from pathlib import Path
import geopandas as gpd
import pandas as pd
EXCLUDED_BASINS = ("guiana", "iceland", "islands")
LAYER_OUTPUT_DIR = {
"River_Net_l": "river_lines",
"River_Net_p": "river_polygons",
"InlandWater": "inland_water",
"RiverBasins": "river_basins",
}
DROP_COLS = {"BEGLIFEVER", "ENDLIFEVER", "UPDAT_BY", "UPDAT_WHEN"}
OUTPUT_DIR = Path("eu_hydro_master_skeleton_geoparquet")
def basin_from_zip(zip_path: str) -> str:
return Path(zip_path).stem.removeprefix("euhydro_").removesuffix("_v013_GPKG")
def extract_gpkg(zip_path: str, dest_dir: Path) -> Path | None:
"""Extract only the primary basin .gpkg from the zip into dest_dir and return its path."""
with zipfile.ZipFile(zip_path) as zf:
names = zf.namelist()
target = next(
(n for n in names if n.lower().endswith(".gpkg") and "drainage_network" not in n.lower()),
None,
)
if target is None:
return None
zf.extract(target, dest_dir)
return dest_dir / target
def process_basin(zip_path: str, target_crs) -> tuple[list[dict], object]:
basin = basin_from_zip(zip_path)
rows: list[dict] = []
tmp_root = Path(tempfile.mkdtemp(prefix=f"euhydro_{basin}_"))
try:
t0 = time.perf_counter()
gpkg = extract_gpkg(zip_path, tmp_root)
if gpkg is None:
print(f" skip {basin}: no matching .gpkg member in zip", flush=True)
return [], target_crs
print(f" extracted in {time.perf_counter() - t0:.1f}s", flush=True)
for layer, subdir in LAYER_OUTPUT_DIR.items():
t1 = time.perf_counter()
try:
gdf = gpd.read_file(gpkg, layer=layer, force_2d=True)
except Exception as e:
print(f" {basin}/{layer}: read failed ({e})", flush=True)
continue
if gdf.empty:
print(f" {basin}/{layer}: empty", flush=True)
continue
if target_crs is None:
target_crs = gdf.crs
elif gdf.crs != target_crs:
gdf = gdf.to_crs(target_crs)
gdf = gdf.drop(columns=[c for c in DROP_COLS if c in gdf.columns])
gdf["source_basin"] = basin
out_dir = OUTPUT_DIR / subdir
out_dir.mkdir(parents=True, exist_ok=True)
out_file = out_dir / f"euhydro_{basin}_v013.geoparquet"
gdf.to_parquet(out_file, index=False, compression="zstd")
n = len(gdf)
rows.append({"layer": layer, "file": f"{subdir}/{out_file.name}", "source_basin": basin, "features": n})
print(f" {basin}/{layer}: {n} features in {time.perf_counter() - t1:.1f}s", flush=True)
finally:
shutil.rmtree(tmp_root, ignore_errors=True)
return rows, target_crs
def main() -> None:
zips = sorted(glob.glob("euhydro_*_v013_GPKG.zip"))
if not zips:
raise RuntimeError("No euhydro_*_v013_GPKG.zip files found in the current directory.")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
target_crs = None
manifest_rows: list[dict] = []
for zp in zips:
basin = basin_from_zip(zp)
if any(x in basin.lower() for x in EXCLUDED_BASINS):
print(f"skipping excluded basin: {basin}", flush=True)
continue
print(f"[{basin}] processing {zp}", flush=True)
rows, target_crs = process_basin(zp, target_crs)
manifest_rows.extend(rows)
if not manifest_rows:
raise RuntimeError("No output files were written.")
manifest_path = OUTPUT_DIR / "manifest.csv"
pd.DataFrame(manifest_rows).sort_values(["layer", "file"]).to_csv(manifest_path, index=False)
print("Done.")
print(f"Wrote {len(manifest_rows)} shards across {len(LAYER_OUTPUT_DIR)} layers to {OUTPUT_DIR}")
print(f"Manifest: {manifest_path}")
if __name__ == "__main__":
main()
|