eu-hydro-master-skeleton / merge_euhydro.py
MartinaAdamuscinova's picture
Duplicate from cassini-team-todo/eu-hydro-master-skeleton
02add7a
Raw
History Blame Contribute Delete
4.46 kB
"""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()