Kossisoroyce's picture
Upload folder using huggingface_hub
f83a5bb verified
Raw
History Blame Contribute Delete
11.2 kB
"""
African Public Debt Management Dataset Validator
Runs plausibility checks and generates 8-panel diagnostic plots.
"""
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.gridspec import GridSpec
OUTPUT_DIR = "data"
PLOT_DIR = os.path.join(OUTPUT_DIR, "plots")
# ── Plausibility thresholds ────────────────────────────────────────────────
CHECKS = {
"debt_to_gdp_pct": (1, 300),
"external_debt_pct": (0, 100),
"domestic_debt_pct": (0, 100),
"debt_service_ratio_pct": (0, 100),
"concessional_debt_pct": (0, 100),
"average_maturity_years": (0.5, 40),
"average_interest_rate_pct": (0, 20),
"debt_sustainability_rating": (1, 5),
"refinancing_risk_score": (0, 100),
"primary_balance_pct": (-20, 15),
"fiscal_space_score": (0, 100),
"gdp_growth_pct": (-15, 20),
"inflation_pct": (0, 100),
"reserves_months_imports": (0, 30),
"revenue_to_gdp_pct": (1, 60),
"expenditure_to_gdp_pct": (2, 70),
}
def run_checks(df: pd.DataFrame) -> list[str]:
"""Run plausibility checks; return list of failure messages."""
failures = []
n = len(df)
# 1. Range checks
for col, (lo, hi) in CHECKS.items():
if col not in df.columns:
failures.append(f"MISSING COLUMN: {col}")
continue
below = (df[col] < lo).sum()
above = (df[col] > hi).sum()
if below > 0:
failures.append(f"RANGE: {col} has {below} values below {lo}")
if above > 0:
failures.append(f"RANGE: {col} has {above} values above {hi}")
# 2. External + domestic ≈ 100
if "external_debt_pct" in df.columns and "domestic_debt_pct" in df.columns:
comp_sum = df["external_debt_pct"] + df["domestic_debt_pct"]
bad = ((comp_sum - 100).abs() > 0.1).sum()
if bad > 0:
failures.append(f"COMPOSITION: {bad} rows where external+domestic ≠ 100%")
# 3. Expenditure > revenue (fiscal deficit)
if "expenditure_to_gdp_pct" in df.columns and "revenue_to_gdp_pct" in df.columns:
exp_lt_rev = (df["expenditure_to_gdp_pct"] < df["revenue_to_gdp_pct"]).sum()
if exp_lt_rev / n > 0.85:
failures.append(
f"FISCAL: {exp_lt_rev}/{n} ({100*exp_lt_rev/n:.1f}%) rows have expenditure < revenue (unusual for SSA)"
)
# 4. No NaN/inf
nan_counts = df.isna().sum()
for col, cnt in nan_counts.items():
if cnt > 0:
failures.append(f"NaN: {col} has {cnt} missing values")
inf_cols = df.select_dtypes(include=[np.number]).columns
for col in inf_cols:
inf_cnt = np.isinf(df[col]).sum()
if inf_cnt > 0:
failures.append(f"INF: {col} has {inf_cnt} infinite values")
# 5. Row count
if len(df) < 25_000:
failures.append(f"SIZE: Dataset has only {len(df)} rows (expected ≥25K)")
# 6. All 12 countries present
expected_countries = {
"Nigeria", "Kenya", "Ghana", "South Africa", "DRC", "Ethiopia",
"Tanzania", "Rwanda", "Mozambique", "Zambia", "Senegal", "Cote d'Ivoire",
}
actual = set(df["country"].unique())
missing = expected_countries - actual
if missing:
failures.append(f"COUNTRIES: Missing: {missing}")
# 7. All 3 scenarios present
expected_scenarios = {"baseline", "debt_consolidation", "debt_distress"}
actual_scenarios = set(df["scenario"].unique())
missing_sc = expected_scenarios - actual_scenarios
if missing_sc:
failures.append(f"SCENARIOS: Missing: {missing_sc}")
# 8. Scenario-specific plausibility
for sc in ["baseline", "debt_consolidation", "debt_distress"]:
sub = df[df["scenario"] == sc]
if len(sub) == 0:
continue
mean_dsr = sub["debt_service_ratio_pct"].mean()
if sc == "debt_distress" and mean_dsr < 15:
failures.append(f"SCENARIO: {sc} mean DSR={mean_dsr:.1f}% seems too low")
if sc == "debt_consolidation" and mean_dsr > 30:
failures.append(f"SCENARIO: {sc} mean DSR={mean_dsr:.1f}% seems too high")
return failures
def generate_diagnostic_plots(df: pd.DataFrame):
"""Generate 8-panel diagnostic figure."""
os.makedirs(PLOT_DIR, exist_ok=True)
plt.style.use("seaborn-v0_8-whitegrid")
fig = plt.figure(figsize=(20, 16))
gs = GridSpec(3, 3, figure=fig, hspace=0.35, wspace=0.30)
colors = {"baseline": "#2196F3", "debt_consolidation": "#4CAF50", "debt_distress": "#F44336"}
# Panel 1: Debt-to-GDP distribution by scenario
ax1 = fig.add_subplot(gs[0, 0])
for sc, c in colors.items():
sub = df[df["scenario"] == sc]
ax1.hist(sub["debt_to_gdp_pct"], bins=50, alpha=0.5, label=sc.replace("_", " ").title(), color=c)
ax1.set_xlabel("Debt-to-GDP (%)")
ax1.set_ylabel("Count")
ax1.set_title("A) Debt-to-GDP Distribution by Scenario")
ax1.legend(fontsize=8)
# Panel 2: Debt service ratio by country
ax2 = fig.add_subplot(gs[0, 1])
country_order = df.groupby("country")["debt_service_ratio_pct"].median().sort_values(ascending=False).index
bp = df.boxplot(
column="debt_service_ratio_pct", by="country", ax=ax2,
vert=True, patch_artist=True, showfliers=False,
positions=range(len(country_order)),
)
ax2.set_xticklabels(country_order, rotation=45, ha="right", fontsize=7)
ax2.set_title("B) Debt Service Ratio by Country")
ax2.set_xlabel("")
plt.sca(ax2)
plt.title("B) Debt Service Ratio by Country")
# Panel 3: External vs Domestic composition
ax3 = fig.add_subplot(gs[0, 2])
for sc, c in colors.items():
sub = df[df["scenario"] == sc]
ax3.scatter(sub["external_debt_pct"], sub["domestic_debt_pct"],
alpha=0.05, s=5, color=c, label=sc.replace("_", " ").title())
ax3.plot([0, 100], [100, 0], "k--", alpha=0.3, linewidth=1)
ax3.set_xlabel("External Debt (%)")
ax3.set_ylabel("Domestic Debt (%)")
ax3.set_title("C) External vs Domestic Debt Composition")
ax3.legend(fontsize=8, markerscale=10)
# Panel 4: Debt sustainability rating distribution
ax4 = fig.add_subplot(gs[1, 0])
for sc, c in colors.items():
sub = df[df["scenario"] == sc]
counts = sub["debt_sustainability_rating"].value_counts().sort_index()
ax4.bar(counts.index + (0.2 if sc == "debt_consolidation" else (-0.2 if sc == "baseline" else 0)),
counts.values, width=0.2, alpha=0.7, color=c, label=sc.replace("_", " ").title())
ax4.set_xlabel("Debt Sustainability Rating (1=Low Risk, 5=Distress)")
ax4.set_ylabel("Count")
ax4.set_title("D) Debt Sustainability Rating Distribution")
ax4.legend(fontsize=8)
# Panel 5: Concessional vs interest rate
ax5 = fig.add_subplot(gs[1, 1])
sample = df.sample(min(5000, len(df)), random_state=42)
for sc, c in colors.items():
sub = sample[sample["scenario"] == sc]
ax5.scatter(sub["concessional_debt_pct"], sub["average_interest_rate_pct"],
alpha=0.3, s=8, color=c)
ax5.set_xlabel("Concessional Debt (%)")
ax5.set_ylabel("Average Interest Rate (%)")
ax5.set_title("E) Concessional Debt vs Interest Rate")
# Panel 6: Refinancing risk vs maturity
ax6 = fig.add_subplot(gs[1, 2])
for sc, c in colors.items():
sub = sample[sample["scenario"] == sc]
ax6.scatter(sub["average_maturity_years"], sub["refinancing_risk_score"],
alpha=0.3, s=8, color=c, label=sc.replace("_", " ").title())
ax6.set_xlabel("Average Maturity (Years)")
ax6.set_ylabel("Refinancing Risk Score")
ax6.set_title("F) Refinancing Risk vs Debt Maturity")
ax6.legend(fontsize=8, markerscale=5)
# Panel 7: Primary balance vs fiscal space
ax7 = fig.add_subplot(gs[2, 0])
for sc, c in colors.items():
sub = sample[sample["scenario"] == sc]
ax7.scatter(sub["primary_balance_pct"], sub["fiscal_space_score"],
alpha=0.3, s=8, color=c)
ax7.set_xlabel("Primary Balance (% GDP)")
ax7.set_ylabel("Fiscal Space Score")
ax7.set_title("G) Primary Balance vs Fiscal Space")
ax7.axvline(0, color="gray", linestyle="--", alpha=0.5)
# Panel 8: Scenario comparison heatmap (mean values)
ax8 = fig.add_subplot(gs[2, 1:])
metrics = [
"debt_to_gdp_pct", "debt_service_ratio_pct", "concessional_debt_pct",
"average_interest_rate_pct", "refinancing_risk_score", "fiscal_space_score",
"primary_balance_pct", "debt_sustainability_rating",
]
scenario_means = df.groupby("scenario")[metrics].mean()
# Normalize for heatmap
normed = (scenario_means - scenario_means.min()) / (scenario_means.max() - scenario_means.min() + 1e-9)
im = ax8.imshow(normed.values, aspect="auto", cmap="RdYlGn_r", vmin=0, vmax=1)
ax8.set_xticks(range(len(metrics)))
ax8.set_xticklabels([m.replace("_", "\n") for m in metrics], fontsize=7, rotation=0, ha="center")
ax8.set_yticks(range(len(scenario_means.index)))
ax8.set_yticklabels([s.replace("_", " ").title() for s in scenario_means.index])
ax8.set_title("H) Scenario Comparison (Normalized Mean Values)")
# Add text annotations
for i in range(len(scenario_means.index)):
for j in range(len(metrics)):
val = scenario_means.values[i, j]
ax8.text(j, i, f"{val:.1f}", ha="center", va="center", fontsize=6,
color="white" if normed.values[i, j] > 0.6 else "black")
fig.suptitle("African Public Debt Management — Diagnostic Plots", fontsize=16, fontweight="bold", y=0.98)
plot_path = os.path.join(PLOT_DIR, "diagnostic_plots.png")
fig.savefig(plot_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Diagnostic plots saved to {plot_path}")
def main():
combined_path = os.path.join(OUTPUT_DIR, "all_scenarios.csv")
if not os.path.exists(combined_path):
print(f"ERROR: {combined_path} not found. Run generate_dataset.py first.")
sys.exit(1)
df = pd.read_csv(combined_path)
print(f"Loaded {len(df)} records from {combined_path}")
print(f" Countries: {df['country'].nunique()}")
print(f" Scenarios: {df['scenario'].unique()}")
print(f" Columns: {len(df.columns)}")
# Run plausibility checks
print("\n── Plausibility Checks ──")
failures = run_checks(df)
if failures:
for f in failures:
print(f" ✗ {f}")
print(f"\n{len(failures)} check(s) failed.")
else:
print(" ✓ All checks passed.")
# Summary statistics
print("\n── Summary Statistics ──")
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
summary = df.groupby("scenario")[numeric_cols].agg(["mean", "std"]).round(2)
print(summary.to_string(max_cols=12))
# Generate plots
print("\n── Generating Diagnostic Plots ──")
generate_diagnostic_plots(df)
return 0 if not failures else 1
if __name__ == "__main__":
sys.exit(main())