""" African Cement Plant Operations Dataset Validator =================================================== Validates data integrity, range checks, cross-field consistency, and scenario-specific properties. """ import pandas as pd import numpy as np import json import os import sys from collections import defaultdict ERRORS = [] WARNINGS = [] def log_error(msg): ERRORS.append(msg) print(f" ERROR: {msg}") def log_warning(msg): WARNINGS.append(msg) print(f" WARNING: {msg}") def log_ok(msg): print(f" OK: {msg}") # --------------------------------------------------------------------------- # 1. File existence checks # --------------------------------------------------------------------------- def check_files_exist(dataset_dir): print("\n=== File Existence Checks ===") required_files = ["baseline.csv", "energy_crisis.csv", "green_transition.csv", "metadata.json"] for f in required_files: path = os.path.join(dataset_dir, f) if os.path.exists(path): log_ok(f"{f} exists") else: log_error(f"{f} is missing") return all(os.path.exists(os.path.join(dataset_dir, f)) for f in required_files) # --------------------------------------------------------------------------- # 2. Record count checks # --------------------------------------------------------------------------- def check_record_counts(dataset_dir): print("\n=== Record Count Checks ===") total = 0 for scenario in ["baseline", "energy_crisis", "green_transition"]: path = os.path.join(dataset_dir, f"{scenario}.csv") df = pd.read_csv(path) count = len(df) total += count if count >= 5000: log_ok(f"{scenario}.csv: {count} records (>= 5000)") else: log_error(f"{scenario}.csv: {count} records (expected >= 5000)") if total >= 15000: log_ok(f"Total records: {total} (>= 15000)") else: log_error(f"Total records: {total} (expected >= 15000)") return total # --------------------------------------------------------------------------- # 3. Schema validation # --------------------------------------------------------------------------- EXPECTED_COLUMNS = [ "plant_id", "country", "region", "scenario", "timestamp", "year", "month", "plant_age_years", "installed_capacity_mt", "grinding_capacity_mt", "capacity_utilization", "clinker_production_tons", "cement_production_tons", "electrical_energy_kwh_per_ton", "thermal_energy_gj_per_ton", "fuel_coal_share", "fuel_gas_share", "fuel_petcoke_share", "fuel_alternative_share", "co2_kg_per_ton_cement", "total_co2_tons_monthly", "maintenance_downtime_hours", "quality_compliance_rate", "cement_type_opc_share", "cement_type_ppc_share", "cement_type_psc_share", "cost_usd_per_ton", "export_volumes_tons", "domestic_sales_tons", "total_revenue_usd", ] def check_schema(dataset_dir): print("\n=== Schema Validation ===") all_ok = True for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) missing = [c for c in EXPECTED_COLUMNS if c not in df.columns] extra = [c for c in df.columns if c not in EXPECTED_COLUMNS] if missing: log_error(f"{scenario}: missing columns: {missing}") all_ok = False else: log_ok(f"{scenario}: all {len(EXPECTED_COLUMNS)} expected columns present") if extra: log_warning(f"{scenario}: extra columns: {extra}") return all_ok # --------------------------------------------------------------------------- # 4. Range checks # --------------------------------------------------------------------------- def check_ranges(dataset_dir): print("\n=== Range Checks ===") all_ok = True checks = { "capacity_utilization": (0.0, 1.0), "plant_age_years": (1.0, 60.0), "clinker_production_tons": (100.0, 5_000_000.0), "cement_production_tons": (100.0, 5_000_000.0), "electrical_energy_kwh_per_ton": (50.0, 150.0), "thermal_energy_gj_per_ton": (2.5, 5.0), "co2_kg_per_ton_cement": (400.0, 850.0), "quality_compliance_rate": (0.70, 1.0), "cost_usd_per_ton": (20.0, 200.0), "maintenance_downtime_hours": (0.0, 200.0), } for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) for col, (lo, hi) in checks.items(): if col not in df.columns: continue out_of_range = ((df[col] < lo) | (df[col] > hi)).sum() if out_of_range > 0: pct = out_of_range / len(df) * 100 if pct < 1.0: log_warning(f"{scenario}/{col}: {out_of_range} values ({pct:.2f}%) outside [{lo}, {hi}]") else: log_error(f"{scenario}/{col}: {out_of_range} values ({pct:.2f}%) outside [{lo}, {hi}]") all_ok = False else: log_ok(f"{scenario}/{col}: all values in [{lo}, {hi}]") return all_ok # --------------------------------------------------------------------------- # 5. Fuel mix sums to 1 # --------------------------------------------------------------------------- def check_fuel_mix(dataset_dir): print("\n=== Fuel Mix Consistency ===") all_ok = True for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) fuel_cols = ["fuel_coal_share", "fuel_gas_share", "fuel_petcoke_share", "fuel_alternative_share"] fuel_sum = df[fuel_cols].sum(axis=1) deviation = (fuel_sum - 1.0).abs() max_dev = deviation.max() if max_dev < 0.01: log_ok(f"{scenario}: fuel mix sums to 1.0 (max deviation: {max_dev:.6f})") else: log_error(f"{scenario}: fuel mix deviation too large (max: {max_dev:.4f})") all_ok = False return all_ok # --------------------------------------------------------------------------- # 6. Cement type shares sum to 1 # --------------------------------------------------------------------------- def check_cement_types(dataset_dir): print("\n=== Cement Type Share Consistency ===") all_ok = True for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) type_cols = ["cement_type_opc_share", "cement_type_ppc_share", "cement_type_psc_share"] type_sum = df[type_cols].sum(axis=1) deviation = (type_sum - 1.0).abs() max_dev = deviation.max() if max_dev < 0.01: log_ok(f"{scenario}: cement type shares sum to 1.0 (max deviation: {max_dev:.6f})") else: log_error(f"{scenario}: cement type shares deviation too large (max: {max_dev:.4f})") all_ok = False return all_ok # --------------------------------------------------------------------------- # 7. Scenario-specific property checks # --------------------------------------------------------------------------- def check_scenario_properties(dataset_dir): print("\n=== Scenario Property Checks ===") all_ok = True baseline = pd.read_csv(os.path.join(dataset_dir, "baseline.csv")) energy_crisis = pd.read_csv(os.path.join(dataset_dir, "energy_crisis.csv")) green = pd.read_csv(os.path.join(dataset_dir, "green_transition.csv")) # Energy crisis should have higher costs baseline_cost = baseline["cost_usd_per_ton"].mean() crisis_cost = energy_crisis["cost_usd_per_ton"].mean() if crisis_cost > baseline_cost * 1.15: log_ok(f"Energy crisis cost ({crisis_cost:.1f}) > baseline cost ({baseline_cost:.1f}) * 1.15") else: log_warning(f"Energy crisis cost ({crisis_cost:.1f}) not sufficiently above baseline ({baseline_cost:.1f})") # Green transition should have lower CO2 baseline_co2 = baseline["co2_kg_per_ton_cement"].mean() green_co2 = green["co2_kg_per_ton_cement"].mean() if green_co2 < baseline_co2 * 0.85: log_ok(f"Green transition CO2 ({green_co2:.1f}) < baseline CO2 ({baseline_co2:.1f}) * 0.85") else: log_warning(f"Green transition CO2 ({green_co2:.1f}) not sufficiently below baseline ({baseline_co2:.1f})") # Green transition should have higher alternative fuels baseline_alt = baseline["fuel_alternative_share"].mean() green_alt = green["fuel_alternative_share"].mean() if green_alt > baseline_alt + 0.10: log_ok(f"Green transition alt fuels ({green_alt:.3f}) > baseline ({baseline_alt:.3f}) + 0.10") else: log_warning(f"Green transition alt fuels ({green_alt:.3f}) not sufficiently above baseline ({baseline_alt:.3f})") # Energy crisis should have lower capacity utilization baseline_util = baseline["capacity_utilization"].mean() crisis_util = energy_crisis["capacity_utilization"].mean() if crisis_util < baseline_util * 0.90: log_ok(f"Energy crisis utilization ({crisis_util:.3f}) < baseline ({baseline_util:.3f}) * 0.90") else: log_warning(f"Energy crisis utilization ({crisis_util:.3f}) not sufficiently below baseline ({baseline_util:.3f})") return all_ok # --------------------------------------------------------------------------- # 8. Country coverage # --------------------------------------------------------------------------- EXPECTED_COUNTRIES = [ "South Africa", "Nigeria", "Egypt", "Morocco", "Kenya", "Ethiopia", "Tanzania", "Senegal", "Algeria", "Cameroon", "Zimbabwe", "Ghana", ] def check_country_coverage(dataset_dir): print("\n=== Country Coverage ===") all_ok = True for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) countries = set(df["country"].unique()) missing = set(EXPECTED_COUNTRIES) - countries if missing: log_error(f"{scenario}: missing countries: {missing}") all_ok = False else: log_ok(f"{scenario}: all {len(EXPECTED_COUNTRIES)} countries present") return all_ok # --------------------------------------------------------------------------- # 9. Temporal coverage # --------------------------------------------------------------------------- def check_temporal_coverage(dataset_dir): print("\n=== Temporal Coverage ===") all_ok = True for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) years = sorted(df["year"].unique()) if years == list(range(2020, 2026)): log_ok(f"{scenario}: covers years 2020-2025") else: log_error(f"{scenario}: years {years} (expected 2020-2025)") all_ok = False months = sorted(df["month"].unique()) if months == list(range(1, 13)): log_ok(f"{scenario}: covers all 12 months") else: log_error(f"{scenario}: months {months} (expected 1-12)") all_ok = False return all_ok # --------------------------------------------------------------------------- # 10. Cross-field consistency # --------------------------------------------------------------------------- def check_cross_field_consistency(dataset_dir): print("\n=== Cross-Field Consistency ===") all_ok = True for scenario in ["baseline", "energy_crisis", "green_transition"]: df = pd.read_csv(os.path.join(dataset_dir, f"{scenario}.csv")) # Cement production should be roughly clinker * clinker_factor # We check that cement_production_tons >= clinker_production_tons * 0.6 ratio = df["cement_production_tons"] / df["clinker_production_tons"] if (ratio < 0.5).sum() == 0: log_ok(f"{scenario}: cement/clinker ratio always >= 0.5") else: log_error(f"{scenario}: {(ratio < 0.5).sum()} records with cement/clinker ratio < 0.5") all_ok = False # Export + domestic should roughly equal total cement production total_sales = df["export_volumes_tons"] + df["domestic_sales_tons"] sales_ratio = total_sales / df["cement_production_tons"] if ((sales_ratio < 0.8) | (sales_ratio > 1.2)).sum() < len(df) * 0.05: log_ok(f"{scenario}: export + domestic ~ cement production (within 20%)") else: log_warning(f"{scenario}: some records with export+domestic far from cement production") # CO2 per ton * cement production / 1000 should roughly equal total CO2 calc_co2 = df["co2_kg_per_ton_cement"] * df["cement_production_tons"] / 1000 co2_deviation = (calc_co2 - df["total_co2_tons_monthly"]).abs() / calc_co2 if (co2_deviation > 0.15).sum() < len(df) * 0.05: log_ok(f"{scenario}: total_co2_tons_monthly consistent with co2_kg_per_ton * production") else: log_warning(f"{scenario}: some CO2 calculations inconsistent") return all_ok # --------------------------------------------------------------------------- # 11. Metadata validation # --------------------------------------------------------------------------- def check_metadata(dataset_dir): print("\n=== Metadata Validation ===") meta_path = os.path.join(dataset_dir, "metadata.json") with open(meta_path) as f: meta = json.load(f) required_keys = ["dataset_name", "description", "version", "total_records", "countries", "scenarios", "time_range", "num_plants", "features"] all_ok = True for key in required_keys: if key in meta: log_ok(f"metadata has '{key}': {meta[key] if not isinstance(meta[key], list) else f'[{len(meta[key])} items]'}") else: log_error(f"metadata missing '{key}'") all_ok = False return all_ok # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def main(): dataset_dir = os.path.dirname(os.path.abspath(__file__)) print(f"Validating dataset at: {dataset_dir}") print("=" * 60) checks = [ check_files_exist, check_record_counts, check_schema, check_ranges, check_fuel_mix, check_cement_types, check_scenario_properties, check_country_coverage, check_temporal_coverage, check_cross_field_consistency, check_metadata, ] results = [] for check_fn in checks: try: result = check_fn(dataset_dir) results.append(result) except Exception as e: log_error(f"Check {check_fn.__name__} failed with exception: {e}") results.append(False) print("\n" + "=" * 60) print(f"VALIDATION SUMMARY") print(f" Checks passed: {sum(results)}/{len(results)}") print(f" Errors: {len(ERRORS)}") print(f" Warnings: {len(WARNINGS)}") if ERRORS: print("\n Errors:") for e in ERRORS: print(f" - {e}") if WARNINGS: print("\n Warnings:") for w in WARNINGS: print(f" - {w}") if all(results) and len(ERRORS) == 0: print("\n VALIDATION PASSED") return 0 else: print("\n VALIDATION FAILED") return 1 if __name__ == "__main__": sys.exit(main())