#!/usr/bin/env python3 """ Script: GetImageRun_3y.py Orchestrates Google Earth Engine exports for DHS cluster points. """ from __future__ import annotations import datetime as dt import os from pathlib import Path import pandas as pd import ee # Local package from satellite_sampling_5k_3y_ctj import export_images # --------------------------------------------------------------------------- # # Configuration # # --------------------------------------------------------------------------- # ROOT_DIR = os.environ.get( 'IMAGEDECONFOUND_REPLICATION_ROOT', str(Path(__file__).resolve().parents[3]) ) INTERIM_DATA_DIR = os.path.join(ROOT_DIR, 'data', 'interim') DATA_DIR = os.environ.get( 'IMAGEDECONFOUND_IMAGE_DOWNLOAD_ROOT', os.path.join(ROOT_DIR, 'external_artifacts', 'images') ) DHS_FILE = os.path.join(INTERIM_DATA_DIR, 'dhs_est_iwi.csv') SPAN_LENGTH_YRS = 3 # each frame is a 3‑year composite NUM_WORKERS = 8 # concurrent EE tasks to launch # --------------------------------------------------------------------------- # # Helper # # --------------------------------------------------------------------------- # def _already_downloaded(row: pd.Series, folder: str, min_bytes: int = 2_600_000) -> bool: """True iff the expected .tif exists and is larger than the safety margin.""" tif = os.path.join(folder, f"{row['dhs_id']}.tif") return os.path.isfile(tif) and os.stat(tif).st_size > min_bytes # --------------------------------------------------------------------------- # # Main # # --------------------------------------------------------------------------- # def main() -> None: os.chdir(ROOT_DIR) # keep relative paths tidy # ---- GEE session ------------------------------------------------------- # ee.Authenticate() # cached after first run ee.Initialize(opt_url='https://earthengine-highvolume.googleapis.com') # ---- Load DHS clusters -------------------------------------------------- # df = pd.read_csv(DHS_FILE) grouped = df.groupby(['country', 'year']) for (country, year), survey_df in grouped: ts = dt.datetime.now().strftime('%d.%b %Y %H:%M:%S') print(f'Downloading images for {country}-{year} … {ts}') out_dir = os.path.join(DATA_DIR, f'dhs_tifs_5k_3yr/{country}_{year}') os.makedirs(out_dir, exist_ok=True) mask = ~survey_df.apply(_already_downloaded, axis=1, folder=out_dir) to_do = survey_df[mask] if to_do.empty: print(f' ✓ all {len(survey_df)} tiles already present') continue export_images(to_do, out_dir, span_length=SPAN_LENGTH_YRS, num_workers=NUM_WORKERS) if __name__ == '__main__': # ***** CRUCIAL for multiprocessing ***** main()