| |
| """ |
| African Civil Service Capacity — Validation & Diagnostic Plots |
| ============================================================== |
| Checks plausibility of generated CSV files and produces summary plots. |
| """ |
|
|
| import os |
| import sys |
| import glob as globmod |
| import numpy as np |
| import pandas as pd |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
| DATA_DIR = os.path.join(os.path.dirname(__file__), "data") |
| PLOT_DIR = os.path.join(DATA_DIR, "plots") |
|
|
| REQUIRED_COLUMNS = [ |
| "record_id", "country", "year", "region_type", "sector", "grade_level", |
| "population_millions", "total_posts", "vacancy_rate", "filled_posts", |
| "degree_rate", "degree_holders", "training_hours_annual", |
| "training_participation_rate", "retention_rate", "avg_salary_usd", |
| "wage_bill_pct_gdp", "performance_eval_rate", "digital_literacy_rate", |
| "capacity_score", "capacity_class", |
| ] |
|
|
| EXPECTED_COUNTRIES = { |
| "South Africa", "Kenya", "Nigeria", "Ghana", "Tanzania", "Uganda", |
| "Rwanda", "Ethiopia", "Senegal", "DRC", "Mozambique", "Botswana", |
| } |
| EXPECTED_REGIONS = {"capital", "urban", "rural", "remote"} |
| EXPECTED_CLASSES = {"high", "moderate", "low", "critical"} |
| EXPECTED_GRADES = {"Junior", "Mid_Level", "Senior", "Director", "Executive"} |
| EXPECTED_SECTORS = { |
| "Health", "Education", "Finance", "Infrastructure", "Agriculture", |
| "Security", "Justice", "Social_Services", "Administration", "ICT", |
| } |
|
|
| RANGE_CHECKS = { |
| "vacancy_rate": (0.05, 0.60), |
| "degree_rate": (0.10, 0.80), |
| "training_participation_rate": (0.20, 0.95), |
| "retention_rate": (0.50, 0.98), |
| "performance_eval_rate": (0.15, 0.95), |
| "digital_literacy_rate": (0.10, 0.90), |
| "capacity_score": (0.0, 1.0), |
| "wage_bill_pct_gdp": (0.0, 0.20), |
| "population_millions": (0.1, 300.0), |
| "avg_salary_usd": (20, 5000), |
| } |
|
|
|
|
| def check_columns(df, filepath): |
| missing = set(REQUIRED_COLUMNS) - set(df.columns) |
| extra = set(df.columns) - set(REQUIRED_COLUMNS) |
| errors = [] |
| if missing: |
| errors.append(f" Missing columns: {missing}") |
| if extra: |
| errors.append(f" Extra columns: {extra}") |
| return errors |
|
|
|
|
| def check_ranges(df, filepath): |
| errors = [] |
| for col, (lo, hi) in RANGE_CHECKS.items(): |
| if col in df.columns: |
| below = (df[col] < lo).sum() |
| above = (df[col] > hi).sum() |
| if below: |
| errors.append(f" {col}: {below} values below {lo}") |
| if above: |
| errors.append(f" {col}: {above} values above {hi}") |
| return errors |
|
|
|
|
| def check_categorical(df, filepath): |
| errors = [] |
| checks = [ |
| ("country", EXPECTED_COUNTRIES), |
| ("region_type", EXPECTED_REGIONS), |
| ("capacity_class", EXPECTED_CLASSES), |
| ("grade_level", EXPECTED_GRADES), |
| ("sector", EXPECTED_SECTORS), |
| ] |
| for col, expected in checks: |
| if col in df.columns: |
| actual = set(df[col].unique()) |
| unexpected = actual - expected |
| if unexpected: |
| errors.append(f" {col}: unexpected values {unexpected}") |
| return errors |
|
|
|
|
| def check_consistency(df, filepath): |
| errors = [] |
| if "filled_posts" in df.columns and "total_posts" in df.columns: |
| bad = (df["filled_posts"] > df["total_posts"]).sum() |
| if bad: |
| errors.append(f" filled_posts > total_posts in {bad} rows") |
| if "degree_holders" in df.columns and "filled_posts" in df.columns: |
| bad = (df["degree_holders"] > df["filled_posts"]).sum() |
| if bad: |
| errors.append(f" degree_holders > filled_posts in {bad} rows") |
| if "capacity_class" in df.columns and "capacity_score" in df.columns: |
| for label, lo, hi in [("high", 0.65, 1.01), ("moderate", 0.50, 0.65), |
| ("low", 0.35, 0.50), ("critical", 0.0, 0.35)]: |
| mask = df["capacity_class"] == label |
| if mask.any(): |
| scores = df.loc[mask, "capacity_score"] |
| out = ((scores < lo) | (scores >= hi)).sum() |
| if out: |
| errors.append(f" capacity_class '{label}': {out} scores outside [{lo:.2f}, {hi:.2f})") |
| return errors |
|
|
|
|
| def print_summary(df, scenario_name): |
| print(f"\n{'='*60}") |
| print(f" {scenario_name} — {len(df)} records") |
| print(f"{'='*60}") |
| print(f" Countries: {sorted(df['country'].unique())}") |
| print(f" Years: {sorted(df['year'].unique())}") |
| print(f" Capacity classes: {df['capacity_class'].value_counts().to_dict()}") |
| print(f" vacancy_rate: mean={df['vacancy_rate'].mean():.4f} std={df['vacancy_rate'].std():.4f}") |
| print(f" degree_rate: mean={df['degree_rate'].mean():.4f} std={df['degree_rate'].std():.4f}") |
| print(f" training_hrs: mean={df['training_hours_annual'].mean():.1f} std={df['training_hours_annual'].std():.1f}") |
| print(f" capacity_score: mean={df['capacity_score'].mean():.4f} std={df['capacity_score'].std():.4f}") |
| print(f" retention_rate: mean={df['retention_rate'].mean():.4f} std={df['retention_rate'].std():.4f}") |
| print(f" digital_lit: mean={df['digital_literacy_rate'].mean():.4f} std={df['digital_literacy_rate'].std():.4f}") |
| print(f" wage_bill_pct: mean={df['wage_bill_pct_gdp'].mean():.4f} std={df['wage_bill_pct_gdp'].std():.4f}") |
| print() |
|
|
|
|
| def make_plots(dfs, names): |
| os.makedirs(PLOT_DIR, exist_ok=True) |
| fig, axes = plt.subplots(2, 3, figsize=(18, 10)) |
| fig.suptitle("African Civil Service Capacity — Scenario Comparison", fontsize=14) |
|
|
| metrics = [ |
| ("vacancy_rate", "Vacancy Rate"), |
| ("degree_rate", "Degree Rate"), |
| ("training_hours_annual", "Training Hours (Annual)"), |
| ("capacity_score", "Capacity Score"), |
| ("retention_rate", "Retention Rate"), |
| ("digital_literacy_rate", "Digital Literacy Rate"), |
| ] |
| colors = ["#2196F3", "#4CAF50", "#FF9800"] |
| for ax, (col, title) in zip(axes.flat, metrics): |
| for df, name, c in zip(dfs, names, colors): |
| ax.hist(df[col], bins=40, alpha=0.45, label=name, color=c, density=True) |
| ax.set_title(title) |
| ax.legend(fontsize=8) |
| ax.set_xlabel(col) |
| ax.set_ylabel("Density") |
| plt.tight_layout() |
| path = os.path.join(PLOT_DIR, "scenario_comparison.png") |
| plt.savefig(path, dpi=150) |
| plt.close() |
| print(f"Saved plot: {path}") |
|
|
| fig, axes = plt.subplots(1, 3, figsize=(18, 5)) |
| fig.suptitle("Capacity Class Distribution by Scenario", fontsize=14) |
| for ax, df, name in zip(axes, dfs, names): |
| counts = df["capacity_class"].value_counts().reindex( |
| ["critical", "low", "moderate", "high"]).fillna(0) |
| counts.plot.bar(ax=ax, color=["#d32f2f", "#FF9800", "#FFC107", "#4CAF50"]) |
| ax.set_title(name) |
| ax.set_ylabel("Count") |
| ax.tick_params(axis='x', rotation=0) |
| plt.tight_layout() |
| path = os.path.join(PLOT_DIR, "capacity_class_distribution.png") |
| plt.savefig(path, dpi=150) |
| plt.close() |
| print(f"Saved plot: {path}") |
|
|
| fig, axes = plt.subplots(1, 3, figsize=(18, 5)) |
| fig.suptitle("Vacancy Rate by Country", fontsize=14) |
| for ax, df, name in zip(axes, dfs, names): |
| df.boxplot(column="vacancy_rate", by="country", ax=ax, rot=45, fontsize=7) |
| ax.set_title(name) |
| ax.set_ylabel("Vacancy Rate") |
| plt.tight_layout() |
| path = os.path.join(PLOT_DIR, "vacancy_by_country.png") |
| plt.savefig(path, dpi=150) |
| plt.close() |
| print(f"Saved plot: {path}") |
|
|
| fig, axes = plt.subplots(1, 3, figsize=(18, 5)) |
| fig.suptitle("Capacity Score by Country", fontsize=14) |
| for ax, df, name in zip(axes, dfs, names): |
| df.boxplot(column="capacity_score", by="country", ax=ax, rot=45, fontsize=7) |
| ax.set_title(name) |
| ax.set_ylabel("Capacity Score") |
| plt.tight_layout() |
| path = os.path.join(PLOT_DIR, "capacity_by_country.png") |
| plt.savefig(path, dpi=150) |
| plt.close() |
| print(f"Saved plot: {path}") |
|
|
|
|
| def main(): |
| csv_files = sorted(globmod.glob(os.path.join(DATA_DIR, "*.csv"))) |
| if not csv_files: |
| print("ERROR: No CSV files found in", DATA_DIR) |
| sys.exit(1) |
|
|
| all_dfs = [] |
| all_names = [] |
| total_errors = 0 |
|
|
| for fpath in csv_files: |
| name = os.path.splitext(os.path.basename(fpath))[0] |
| df = pd.read_csv(fpath) |
| all_dfs.append(df) |
| all_names.append(name) |
|
|
| print(f"\n>>> Validating {fpath} ({len(df)} rows)") |
| errors = [] |
| errors += check_columns(df, fpath) |
| errors += check_ranges(df, fpath) |
| errors += check_categorical(df, fpath) |
| errors += check_consistency(df, fpath) |
|
|
| if errors: |
| print(" FAILURES:") |
| for e in errors: |
| print(e) |
| total_errors += len(errors) |
| else: |
| print(" All checks passed.") |
|
|
| print_summary(df, name) |
|
|
| make_plots(all_dfs, all_names) |
|
|
| print(f"\n{'='*60}") |
| if total_errors == 0: |
| print("ALL VALIDATION CHECKS PASSED") |
| else: |
| print(f"VALIDATION COMPLETE — {total_errors} issue(s) found") |
| print(f"{'='*60}") |
| sys.exit(0 if total_errors == 0 else 1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|