#!/usr/bin/env python3 """Validate the African crop insurance payouts dataset.""" import csv import json import os import sys EXPECTED_COLUMNS = [ "record_id", "country", "year", "season", "crop_type", "insurance_type", "scenario", "enrolled_hectares", "premium_paid_usd", "ndvi_anomaly", "rainfall_deficit_pct", "yield_loss_pct", "payout_triggered", "payout_amount_usd", "payout_ratio", "farmer_count", "enrollment_rate", "lapse_rate", "basis_risk_score", ] VALID_COUNTRIES = { "Kenya", "Ethiopia", "Tanzania", "Malawi", "Zambia", "Zimbabwe", "Mozambique", "Senegal", "Ghana", "Nigeria", "Rwanda", "Uganda", } VALID_CROPS = {"maize", "wheat", "sorghum", "rice", "cassava"} VALID_INSURANCE = {"index_based", "area_yield", "weather_derivative"} VALID_SCENARIOS = {"baseline", "expanded_index_insurance", "climate_shock"} VALID_SEASONS = {"long_rains", "short_rains"} def validate(data_dir): csv_path = os.path.join(data_dir, "african_crop_insurance_payouts.csv") meta_path = os.path.join(data_dir, "..", "metadata.json") errors = [] warnings = [] # --- File existence --- if not os.path.exists(csv_path): errors.append(f"CSV not found: {csv_path}") return errors, warnings # --- Read CSV --- with open(csv_path, newline="") as f: reader = csv.DictReader(f) rows = list(reader) print(f"Loaded {len(rows)} records") # --- Column check --- if reader.fieldnames != EXPECTED_COLUMNS: missing = set(EXPECTED_COLUMNS) - set(reader.fieldnames) extra = set(reader.fieldnames) - set(EXPECTED_COLUMNS) if missing: errors.append(f"Missing columns: {missing}") if extra: warnings.append(f"Extra columns: {extra}") # --- Record count --- if len(rows) != 30000: errors.append(f"Expected 30000 records, got {len(rows)}") # --- Per-scenario counts --- scenario_counts = {} for r in rows: s = r["scenario"] scenario_counts[s] = scenario_counts.get(s, 0) + 1 for s in VALID_SCENARIOS: if s not in scenario_counts: errors.append(f"Missing scenario: {s}") elif scenario_counts[s] < 9900 or scenario_counts[s] > 10100: warnings.append(f"Scenario '{s}' has {scenario_counts[s]} records (~10000 expected)") # --- Per-record validation --- record_ids = set() for i, r in enumerate(rows): row_num = i + 1 # Unique record_id rid = r["record_id"] if rid in record_ids: errors.append(f"Row {row_num}: duplicate record_id {rid}") record_ids.add(rid) # Country if r["country"] not in VALID_COUNTRIES: errors.append(f"Row {row_num}: invalid country '{r['country']}'") # Year try: year = int(r["year"]) if year < 2015 or year > 2024: warnings.append(f"Row {row_num}: year {year} outside 2015-2024") except ValueError: errors.append(f"Row {row_num}: non-integer year '{r['year']}'") # Season if r["season"] not in VALID_SEASONS: errors.append(f"Row {row_num}: invalid season '{r['season']}'") # Crop type if r["crop_type"] not in VALID_CROPS: errors.append(f"Row {row_num}: invalid crop_type '{r['crop_type']}'") # Insurance type if r["insurance_type"] not in VALID_INSURANCE: errors.append(f"Row {row_num}: invalid insurance_type '{r['insurance_type']}'") # Scenario if r["scenario"] not in VALID_SCENARIOS: errors.append(f"Row {row_num}: invalid scenario '{r['scenario']}'") # Numeric ranges try: hectares = float(r["enrolled_hectares"]) if hectares < 0.2 or hectares > 20: warnings.append(f"Row {row_num}: hectares {hectares} outside [0.2, 20]") except ValueError: errors.append(f"Row {row_num}: non-numeric enrolled_hectares") try: premium = float(r["premium_paid_usd"]) if premium < 0: errors.append(f"Row {row_num}: negative premium {premium}") except ValueError: errors.append(f"Row {row_num}: non-numeric premium_paid_usd") try: ndvi = float(r["ndvi_anomaly"]) if ndvi < -3.5 or ndvi > 2.5: warnings.append(f"Row {row_num}: extreme ndvi_anomaly {ndvi}") except ValueError: errors.append(f"Row {row_num}: non-numeric ndvi_anomaly") try: rd = float(r["rainfall_deficit_pct"]) if rd < 0 or rd > 100: warnings.append(f"Row {row_num}: rainfall_deficit_pct {rd} outside [0,100]") except ValueError: errors.append(f"Row {row_num}: non-numeric rainfall_deficit_pct") try: yl = float(r["yield_loss_pct"]) if yl < 0 or yl > 100: warnings.append(f"Row {row_num}: yield_loss_pct {yl} outside [0,100]") except ValueError: errors.append(f"Row {row_num}: non-numeric yield_loss_pct") # Payout consistency triggered = r["payout_triggered"] == "True" try: payout_amt = float(r["payout_amount_usd"]) payout_rat = float(r["payout_ratio"]) if triggered and payout_amt <= 0: errors.append(f"Row {row_num}: payout triggered but amount <= 0") if not triggered and payout_amt != 0: errors.append(f"Row {row_num}: payout not triggered but amount != 0") if triggered and payout_rat <= 0: errors.append(f"Row {row_num}: payout triggered but ratio <= 0") if not triggered and payout_rat != 0: errors.append(f"Row {row_num}: payout not triggered but ratio != 0") except ValueError: errors.append(f"Row {row_num}: non-numeric payout fields") # Enrollment rate try: er = float(r["enrollment_rate"]) if er < 0 or er > 1: errors.append(f"Row {row_num}: enrollment_rate {er} outside [0,1]") except ValueError: errors.append(f"Row {row_num}: non-numeric enrollment_rate") # Lapse rate try: lr = float(r["lapse_rate"]) if lr < 0 or lr > 1: errors.append(f"Row {row_num}: lapse_rate {lr} outside [0,1]") except ValueError: errors.append(f"Row {row_num}: non-numeric lapse_rate") # Basis risk try: br = float(r["basis_risk_score"]) if br < 0 or br > 1: errors.append(f"Row {row_num}: basis_risk_score {br} outside [0,1]") except ValueError: errors.append(f"Row {row_num}: non-numeric basis_risk_score") # --- Metadata check --- if os.path.exists(meta_path): with open(meta_path) as f: meta = json.load(f) if "variables" not in meta: warnings.append("metadata.json missing 'variables' key") if meta.get("license") != "CC-BY-4.0": warnings.append(f"Unexpected license: {meta.get('license')}") else: warnings.append("metadata.json not found") # --- Summary stats --- payouts = [r for r in rows if r["payout_triggered"] == "True"] print(f"\nDataset Statistics:") print(f" Total records: {len(rows)}") print(f" Payouts triggered: {len(payouts)} ({100*len(payouts)/len(rows):.1f}%)") print(f" Countries: {len(set(r['country'] for r in rows))}") print(f" Scenarios: {scenario_counts}") print(f" Unique IDs: {len(record_ids)}") return errors, warnings if __name__ == "__main__": data_dir = os.path.join(os.path.dirname(__file__), "data") errors, warnings = validate(data_dir) print(f"\n{'='*50}") if errors: print(f"FAIL: {len(errors)} error(s)") for e in errors[:10]: print(f" ✗ {e}") if len(errors) > 10: print(f" ... and {len(errors)-10} more") sys.exit(1) else: print("PASS: No errors") if warnings: print(f" {len(warnings)} warning(s)") for w in warnings[:5]: print(f" ⚠ {w}") else: print(" No warnings")