Kossisoroyce's picture
Upload folder using huggingface_hub
8b85d05 verified
Raw
History Blame Contribute Delete
25.3 kB
#!/usr/bin/env python3
"""
African Judicial Access Indicators — Synthetic Dataset Generator
================================================================
Electric Sheep Africa | electricsheepafrica on HuggingFace
Generates synthetic judicial access indicator data for sub-Saharan African
countries at the subnational (region) level, parameterized from peer-reviewed
literature, WJP indices, Afrobarometer surveys, and national reports.
PHASE 2 — Causal & Correlation Structure (DAG)
================================================
ROOT NODES (sampled independently):
├── country → Categorical (weighted by population)
├── year → Uniform [2018–2025]
└── region_type → Categorical {urban, peri_urban, rural, remote_rural}
INTERMEDIATE NODES (sampled conditionally):
├── population → Conditional on country, year
├── lawyer_density → Conditional on country tier, region_type [Ref 16]
├── court_density → Conditional on country tier, region_type
├── distance_to_court → Conditional on region_type, court_density [Ref 1]
├── travel_time_hours → Conditional on distance, region_type
├── legal_aid_coverage→ Conditional on country tier, region_type [Refs 6,7]
├── legal_aid_per_cap → Conditional on country tier [Ref 10]
├── paralegal_density → Conditional on country, region_type [Ref 4]
├── cost_pct_income → Conditional on region_type, country tier [Ref 2]
├── bribery_rate → Conditional on country tier [Ref 9]
└── gender_access_ratio → Conditional on country tier, region_type [Ref 12,15]
LEAF NODES (derived / looked up):
├── court_contact_rate → Conditional on distance, cost, trust [Ref 9]
├── trust_in_courts → Conditional on bribery, country tier [Ref 9]
├── customary_justice_use → Conditional on region_type, legal_aid [Ref 6]
├── wjp_score → Looked up by country with noise [Ref 5]
└── access_level → Classification: high, moderate, low, very_low
CORRELATION TARGET MATRIX (lower triangle):
lawyer_d court_d distance legal_aid cost bribery trust
lawyer_dens 1.00
court_dens 0.50 1.00
distance -0.40 -0.60 1.00
legal_aid 0.45 0.35 -0.35 1.00
cost_pct -0.30 -0.25 0.40 -0.35 1.00
bribery -0.35 -0.30 0.25 -0.40 0.30 1.00
trust 0.25 0.30 -0.20 0.35 -0.25 -0.60 1.00
Sources: Afrobarometer R6 [Ref 9] for trust-bribery r≈-0.6; distance-contact
inverse from Benyawa 2023 [Ref 1]; Soboka 2019 [Ref 2] for cost barriers.
References
----------
[1] Benyawa (2023), "How Far Are Kenya's Courts?", J. of African Law
[2] Soboka (2019), "What does justice cost in South Africa?", SA J. Human Rights
[3] Bilchitz & Williams (2020), PER/PELJ
[4] Cambridge UP (2018), Community Paralegals and the Pursuit of Justice
[5] World Justice Project, Rule of Law Index 2024/2025
[6] UNODC (2011), Access to Legal Aid in Africa
[7] UNDP (2014), Legal Aid Service Provision in Africa
[8] UNODC (2014), Handbook on Legal Aid in Africa
[9] Afrobarometer (2017), Policy Paper No. 39
[10] Legal Aid South Africa, Annual Report 2022/23
[11] HiiL (2023), Justice Needs Survey: Nigeria
[12] UN Women (2021), Access to Justice for Women ESA
[13] World Bank (2019), Cost-Benefit Analysis of Legal Aid
[14] ACCORD (2012), Abunzi Mediation in Rwanda
[15] Brookings (2022), Women and Access to Justice in Africa
[16] World Population Review (2026), Lawyers per Capita
[17] NYU CIC (2023), Front-line Justice Services Policy Brief
"""
import argparse
import os
import sys
import numpy as np
import pandas as pd
# ============================================================================
# SECTION 1: LITERATURE-INFORMED PARAMETERS
# ============================================================================
# --- 1A. Country metadata ---
# WJP scores [Ref 5], lawyer density [Ref 16], access tier
COUNTRIES = {
"South Africa": {"pop_2024": 62.0, "wjp": 0.56, "tier": "high", "growth": 0.008,
"lawyer_density": 37.04, "legal_aid_pc": 2.25},
"Botswana": {"pop_2024": 2.6, "wjp": 0.60, "tier": "high", "growth": 0.015,
"lawyer_density": 25.0, "legal_aid_pc": 1.50},
"Mauritius": {"pop_2024": 1.3, "wjp": 0.60, "tier": "high", "growth": 0.001,
"lawyer_density": 45.21, "legal_aid_pc": 1.80},
"Rwanda": {"pop_2024": 14.0, "wjp": 0.63, "tier": "high", "growth": 0.024,
"lawyer_density": 10.0, "legal_aid_pc": 0.40},
"Kenya": {"pop_2024": 55.0, "wjp": 0.45, "tier": "moderate", "growth": 0.021,
"lawyer_density": 15.82, "legal_aid_pc": 0.02},
"Ghana": {"pop_2024": 34.0, "wjp": 0.54, "tier": "moderate", "growth": 0.021,
"lawyer_density": 7.26, "legal_aid_pc": 0.03},
"Tanzania": {"pop_2024": 67.0, "wjp": 0.46, "tier": "moderate", "growth": 0.030,
"lawyer_density": 4.0, "legal_aid_pc": 0.05},
"Senegal": {"pop_2024": 18.0, "wjp": 0.56, "tier": "moderate", "growth": 0.027,
"lawyer_density": 6.5, "legal_aid_pc": 0.04},
"Nigeria": {"pop_2024": 230.0,"wjp": 0.41, "tier": "low", "growth": 0.025,
"lawyer_density": 11.0, "legal_aid_pc": 0.01},
"DRC": {"pop_2024": 105.0,"wjp": 0.34, "tier": "low", "growth": 0.032,
"lawyer_density": 13.93, "legal_aid_pc": 0.005},
"Uganda": {"pop_2024": 49.0, "wjp": 0.38, "tier": "low", "growth": 0.032,
"lawyer_density": 5.0, "legal_aid_pc": 0.02},
"Malawi": {"pop_2024": 21.0, "wjp": 0.52, "tier": "low", "growth": 0.026,
"lawyer_density": 2.5, "legal_aid_pc": 0.02},
"Mozambique": {"pop_2024": 33.0, "wjp": 0.37, "tier": "low", "growth": 0.028,
"lawyer_density": 2.0, "legal_aid_pc": 0.005},
}
# --- 1B. Region type distribution ---
# SSA: ~35-40% urban, 60-65% rural [World Bank]
REGION_TYPES = {
"urban": 0.20,
"peri_urban": 0.18,
"rural": 0.42,
"remote_rural": 0.20,
}
# --- 1C. Distance to court by region type (km) [Ref 1: Kenya avg 22km] ---
DISTANCE_KM = {
"urban": {"mean": 5, "sd": 3, "min": 0.5, "max": 20},
"peri_urban": {"mean": 15, "sd": 8, "min": 3, "max": 40},
"rural": {"mean": 40, "sd": 20, "min": 10, "max": 100},
"remote_rural": {"mean": 90, "sd": 40, "min": 30, "max": 250},
}
# Tier multiplier for distance [low-access countries have worse infrastructure]
DISTANCE_TIER_MULT = {"high": 0.7, "moderate": 1.0, "low": 1.4}
# --- 1D. Travel time model: time = distance / speed + overhead ---
# Speed varies by region type and infrastructure quality
TRAVEL_SPEED_KPH = {
"urban": {"mean": 20, "sd": 5}, # congested, public transport
"peri_urban": {"mean": 25, "sd": 8},
"rural": {"mean": 15, "sd": 5}, # poor roads, mixed transport
"remote_rural": {"mean": 10, "sd": 4}, # walking, motorbike, boat
}
TRAVEL_OVERHEAD_HOURS = {
"urban": 0.2, "peri_urban": 0.3, "rural": 0.5, "remote_rural": 1.0,
}
# --- 1E. Lawyer density by region type [Ref 16: >80% concentrated in capitals] ---
# Multiplier applied to country's national lawyer_density
LAWYER_REGION_MULT = {
"urban": 2.5, # Capital/city concentration [Ref 16]
"peri_urban": 1.0,
"rural": 0.2,
"remote_rural": 0.05, # Near zero in remote areas
}
# --- 1F. Court density per 100K by tier [Refs from Phase 1] ---
# SA: ~1.17; Tanzania: ~1.2-1.5; Rwanda: ~3.0 (formal); Kenya: ~0.22; DRC: <0.10
COURT_DENSITY = {
"high": {"mean": 2.0, "sd": 0.8, "min": 0.5, "max": 5.0},
"moderate": {"mean": 0.8, "sd": 0.4, "min": 0.1, "max": 2.0},
"low": {"mean": 0.3, "sd": 0.2, "min": 0.05, "max": 1.0},
}
COURT_REGION_MULT = {
"urban": 2.0, "peri_urban": 1.2, "rural": 0.5, "remote_rural": 0.15,
}
# --- 1G. Legal aid coverage % [Refs 6, 7, 10] ---
LEGAL_AID_COVERAGE = {
"high": {"mean": 20, "sd": 8, "min": 5, "max": 40},
"moderate": {"mean": 7, "sd": 3, "min": 2, "max": 15},
"low": {"mean": 3, "sd": 2, "min": 0.5,"max": 8},
}
LEGAL_AID_REGION_MULT = {
"urban": 2.0, "peri_urban": 1.0, "rural": 0.4, "remote_rural": 0.1,
}
# --- 1H. Paralegal / community justice density per 100K [Refs 4, 14, 17] ---
# Rwanda: 270/100K (Abunzi); SA: ~1-2; Uganda: ~1-2; Kenya: ~1-3
PARALEGAL_DENSITY = {
"high": {"mean": 30, "sd": 60, "min": 1, "max": 300}, # Rwanda pulls mean up
"moderate": {"mean": 3, "sd": 2, "min": 0.5, "max": 10},
"low": {"mean": 1, "sd": 1, "min": 0.1, "max": 5},
}
# --- 1I. Cost of justice as % monthly income [Ref 2: SA 250% for poor] ---
COST_PCT_INCOME = {
"urban": {"mean": 60, "sd": 40, "min": 10, "max": 250},
"peri_urban": {"mean": 100, "sd": 50, "min": 15, "max": 350},
"rural": {"mean": 150, "sd": 70, "min": 25, "max": 450},
"remote_rural": {"mean": 200, "sd": 90, "min": 40, "max": 550},
}
COST_TIER_MULT = {"high": 0.6, "moderate": 1.0, "low": 1.4}
# --- 1J. Bribery rate % [Ref 9: Afrobarometer 30% SSA avg] ---
BRIBERY_RATE = {
"high": {"mean": 15, "sd": 5, "min": 5, "max": 30},
"moderate": {"mean": 28, "sd": 8, "min": 10, "max": 45},
"low": {"mean": 40, "sd": 10, "min": 15, "max": 60},
}
# --- 1K. Trust in courts % [Ref 9: SSA avg 53%; Tanzania 88%; Southern Africa 25%] ---
TRUST_COURTS = {
"high": {"mean": 70, "sd": 12, "min": 40, "max": 95},
"moderate": {"mean": 50, "sd": 12, "min": 25, "max": 75},
"low": {"mean": 35, "sd": 10, "min": 15, "max": 55},
}
# --- 1L. Gender access ratio (women/men) [Refs 12, 15: 64% globally] ---
GENDER_ACCESS = {
"high": {"mean": 0.85, "sd": 0.06, "min": 0.65, "max": 0.98},
"moderate": {"mean": 0.72, "sd": 0.08, "min": 0.50, "max": 0.90},
"low": {"mean": 0.58, "sd": 0.08, "min": 0.40, "max": 0.78},
}
GENDER_REGION_MULT = {
"urban": 1.10, "peri_urban": 1.0, "rural": 0.90, "remote_rural": 0.80,
}
# --- 1M. Customary justice use % [Ref 6: Malawi 80-90% rural] ---
CUSTOMARY_USE = {
"urban": {"mean": 15, "sd": 8, "min": 2, "max": 35},
"peri_urban": {"mean": 30, "sd": 12, "min": 10, "max": 55},
"rural": {"mean": 60, "sd": 15, "min": 25, "max": 85},
"remote_rural": {"mean": 80, "sd": 10, "min": 50, "max": 98},
}
# --- 1N. Access level classification ---
# Composite score = weighted combination of indicators
# Thresholds calibrated so baseline produces ~15-25% each tier
ACCESS_LEVELS = {
"high": (0.55, 1.01),
"moderate": (0.38, 0.55),
"low": (0.22, 0.38),
"very_low": (0.00, 0.22),
}
# --- 1O. Scenario definitions ---
SCENARIOS = {
"baseline": {
"description": "Current SSA judicial access landscape (2018-2025)",
"distance_mult": 1.0, "lawyer_mult": 1.0, "legal_aid_mult": 1.0,
"cost_mult": 1.0, "paralegal_mult": 1.0,
},
"improved_access": {
"description": "Countries investing in justice reform and legal aid expansion",
"distance_mult": 0.8, "lawyer_mult": 1.3, "legal_aid_mult": 1.5,
"cost_mult": 0.7, "paralegal_mult": 2.0,
},
"constrained": {
"description": "Fiscal austerity / conflict reducing access to justice",
"distance_mult": 1.2, "lawyer_mult": 0.8, "legal_aid_mult": 0.5,
"cost_mult": 1.5, "paralegal_mult": 0.6,
},
}
# WJP annual noise [Ref 5]
WJP_ANNUAL_NOISE_SD = 0.015
# ============================================================================
# SECTION 2: UTILITY FUNCTIONS
# ============================================================================
def trunc_normal(rng, mean, sd, low, high, size=1):
"""Sample from truncated normal distribution."""
from scipy.stats import truncnorm
if sd <= 0:
return np.full(size, mean)
a = (low - mean) / sd
b = (high - mean) / sd
return truncnorm.rvs(a, b, loc=mean, scale=sd, size=size, random_state=rng)
def sample_categorical(rng, categories, probabilities, size=1):
"""Weighted categorical sampling."""
probs = np.array(probabilities, dtype=float)
probs /= probs.sum()
return rng.choice(categories, size=size, p=probs)
def classify_access(score):
"""Classify access level from composite score."""
for label, (lo, hi) in ACCESS_LEVELS.items():
if lo <= score < hi:
return label
return "very_low"
# ============================================================================
# SECTION 3: MAIN GENERATOR FUNCTION
# ============================================================================
def generate_judicial_access_data(scenario_name="baseline", n=10000, seed=42):
"""
Generate synthetic African judicial access indicator records.
SAMPLING ORDER (topological sort of DAG):
─────────────────────────────────────────
1. [Root] → sample country
2. [Root] → sample year
3. [Root] → sample region_type
4. [Intermediate] → sample lawyer_density | country, region
5. [Intermediate] → sample court_density | tier, region
6. [Intermediate] → sample distance_to_court | region, tier
7. [Intermediate] → derive travel_time | distance, region
8. [Intermediate] → sample legal_aid_coverage | tier, region
9. [Intermediate] → lookup legal_aid_per_capita | country
10. [Intermediate] → sample paralegal_density | tier, country
11. [Intermediate] → sample cost_pct_income | region, tier
12. [Intermediate] → sample bribery_rate | tier
13. [Intermediate] → sample gender_access_ratio | tier, region
14. [Intermediate] → sample customary_justice_use | region
15. [Leaf] → derive trust_in_courts | bribery, tier
16. [Leaf] → derive court_contact_rate | distance, cost, trust
17. [Leaf] → lookup wjp_score | country, year
18. [Leaf] → derive access_score & classify access_level
─────────────────────────────────────────
"""
rng = np.random.default_rng(seed)
scenario = SCENARIOS[scenario_name]
# --- Root nodes ---
country_names = list(COUNTRIES.keys())
country_pops = np.array([COUNTRIES[c]["pop_2024"] for c in country_names])
countries = sample_categorical(rng, country_names, country_pops / country_pops.sum(), size=n)
years = rng.integers(2018, 2026, size=n)
region_names = list(REGION_TYPES.keys())
region_probs = list(REGION_TYPES.values())
regions = sample_categorical(rng, region_names, region_probs, size=n)
# Pre-allocate
cols = {}
lawyer_density = np.zeros(n)
court_density = np.zeros(n)
distance_km = np.zeros(n)
travel_time = np.zeros(n)
legal_aid_cov = np.zeros(n)
legal_aid_pc = np.zeros(n)
paralegal_dens = np.zeros(n)
cost_pct = np.zeros(n)
bribery = np.zeros(n)
gender_ratio = np.zeros(n)
customary_use = np.zeros(n)
trust = np.zeros(n)
contact_rate = np.zeros(n)
wjp = np.zeros(n)
access_score = np.zeros(n)
access_level = np.empty(n, dtype=object)
for i in range(n):
c = countries[i]
r = regions[i]
meta = COUNTRIES[c]
tier = meta["tier"]
# Step 4: Lawyer density | country, region [Ref 16]
base_ld = meta["lawyer_density"] * scenario["lawyer_mult"]
ld = base_ld * LAWYER_REGION_MULT[r]
ld += rng.normal(0, ld * 0.2) # 20% noise
lawyer_density[i] = round(np.clip(ld, 0.01, 150), 2)
# Step 5: Court density | tier, region
cd_params = COURT_DENSITY[tier]
cd = trunc_normal(rng, cd_params["mean"], cd_params["sd"],
cd_params["min"], cd_params["max"])[0]
cd *= COURT_REGION_MULT[r]
court_density[i] = round(np.clip(cd, 0.01, 15), 3)
# Step 6: Distance to court | region, tier [Ref 1]
d_params = DISTANCE_KM[r]
d = trunc_normal(rng, d_params["mean"] * DISTANCE_TIER_MULT[tier] * scenario["distance_mult"],
d_params["sd"], d_params["min"], d_params["max"])[0]
# Inverse relationship with court density
if court_density[i] > 0.5:
d *= 0.8
distance_km[i] = round(np.clip(d, 0.5, 300), 1)
# Step 7: Travel time | distance, region
spd_params = TRAVEL_SPEED_KPH[r]
speed = max(rng.normal(spd_params["mean"], spd_params["sd"]), 2)
overhead = TRAVEL_OVERHEAD_HOURS[r]
tt = distance_km[i] / speed + overhead
travel_time[i] = round(np.clip(tt, 0.1, 48), 2)
# Step 8: Legal aid coverage | tier, region [Refs 6, 7]
la_params = LEGAL_AID_COVERAGE[tier]
la = trunc_normal(rng, la_params["mean"] * scenario["legal_aid_mult"],
la_params["sd"], la_params["min"],
la_params["max"] * scenario["legal_aid_mult"])[0]
la *= LEGAL_AID_REGION_MULT[r]
legal_aid_cov[i] = round(np.clip(la, 0.1, 60), 1)
# Step 9: Legal aid per capita | country [Ref 10]
la_pc = meta["legal_aid_pc"] * scenario["legal_aid_mult"]
la_pc *= rng.lognormal(0, 0.3)
legal_aid_pc[i] = round(np.clip(la_pc, 0.001, 10.0), 3)
# Step 10: Paralegal density | tier [Refs 4, 14, 17]
pl_params = PARALEGAL_DENSITY[tier]
# Rwanda special case: Abunzi system [Ref 14]
if c == "Rwanda":
pl = trunc_normal(rng, 270 * scenario["paralegal_mult"], 50, 100, 400)[0]
else:
pl = trunc_normal(rng, pl_params["mean"] * scenario["paralegal_mult"],
pl_params["sd"], pl_params["min"], pl_params["max"])[0]
paralegal_dens[i] = round(np.clip(pl, 0.05, 400), 1)
# Step 11: Cost as % monthly income | region, tier [Ref 2]
cost_params = COST_PCT_INCOME[r]
co = trunc_normal(rng, cost_params["mean"] * COST_TIER_MULT[tier] * scenario["cost_mult"],
cost_params["sd"], cost_params["min"], cost_params["max"])[0]
cost_pct[i] = round(np.clip(co, 5, 700), 0)
# Step 12: Bribery rate | tier [Ref 9]
br_params = BRIBERY_RATE[tier]
br = trunc_normal(rng, br_params["mean"], br_params["sd"],
br_params["min"], br_params["max"])[0]
bribery[i] = round(np.clip(br, 1, 70), 1)
# Step 13: Gender access ratio | tier, region [Refs 12, 15]
ga_params = GENDER_ACCESS[tier]
ga = trunc_normal(rng, ga_params["mean"], ga_params["sd"],
ga_params["min"], ga_params["max"])[0]
ga *= GENDER_REGION_MULT[r]
gender_ratio[i] = round(np.clip(ga, 0.30, 1.0), 3)
# Step 14: Customary justice use | region [Ref 6]
cj_params = CUSTOMARY_USE[r]
cj = trunc_normal(rng, cj_params["mean"], cj_params["sd"],
cj_params["min"], cj_params["max"])[0]
customary_use[i] = round(np.clip(cj, 1, 99), 1)
# Step 15: Trust in courts | bribery, tier [Ref 9]
# Trust inversely related to bribery: r ≈ -0.6
tr_params = TRUST_COURTS[tier]
tr_base = trunc_normal(rng, tr_params["mean"], tr_params["sd"],
tr_params["min"], tr_params["max"])[0]
# Inject bribery effect: higher bribery → lower trust
bribery_effect = -0.6 * (bribery[i] - 30) # centered on SSA avg 30%
tr = tr_base + bribery_effect
trust[i] = round(np.clip(tr, 10, 98), 1)
# Step 16: Court contact rate | distance, cost, trust [Ref 9]
# SSA avg: 13%; range 4-28%. Weaker effects + more noise to avoid
# overly mechanical correlations.
base_contact = 13.0
# Distance penalty: each 10km above 20 reduces by 0.3pp
dist_effect = -0.3 * max(0, (distance_km[i] - 20)) / 10
# Cost penalty: each 50% above 100% reduces by 0.5pp
cost_effect = -0.5 * max(0, (cost_pct[i] - 100)) / 50
# Trust bonus: each 10pp above 50% adds 0.6pp
trust_effect = 0.6 * (trust[i] - 50) / 10
cr = base_contact + dist_effect + cost_effect + trust_effect
cr += rng.normal(0, 5) # larger noise to decouple
contact_rate[i] = round(np.clip(cr, 1, 40), 1)
# Step 17: WJP score | country, year [Ref 5]
base_wjp = meta["wjp"]
years_to_2025 = 2025 - years[i]
wjp_noise = rng.normal(0, WJP_ANNUAL_NOISE_SD * np.sqrt(years_to_2025 + 1))
wjp[i] = round(np.clip(base_wjp + wjp_noise, 0.15, 0.90), 3)
# Step 18: Access score & classification
# Composite: normalize each indicator to [0,1] and weight
ld_norm = np.clip(lawyer_density[i] / 50, 0, 1) # 50/100K = best
cd_norm = np.clip(court_density[i] / 3.0, 0, 1) # 3/100K = best
dist_norm = 1 - np.clip(distance_km[i] / 150, 0, 1) # 0km = best
la_norm = np.clip(legal_aid_cov[i] / 30, 0, 1) # 30% = best
cost_norm = 1 - np.clip(cost_pct[i] / 500, 0, 1) # 0% = best
trust_norm = np.clip(trust[i] / 100, 0, 1) # 100% = best
bribe_norm = 1 - np.clip(bribery[i] / 60, 0, 1) # 0% = best
gender_norm = np.clip(gender_ratio[i], 0, 1)
score = (0.15 * ld_norm + 0.15 * cd_norm + 0.15 * dist_norm +
0.15 * la_norm + 0.10 * cost_norm + 0.10 * trust_norm +
0.10 * bribe_norm + 0.10 * gender_norm)
access_score[i] = round(score, 3)
access_level[i] = classify_access(score)
# --- Assemble DataFrame ---
df = pd.DataFrame({
"record_id": np.arange(1, n + 1),
"country": countries,
"year": years,
"region_type": regions,
"lawyer_density_per_100k": lawyer_density,
"court_density_per_100k": court_density,
"distance_to_court_km": distance_km,
"travel_time_hours": travel_time,
"legal_aid_coverage_pct": legal_aid_cov,
"legal_aid_per_capita_usd": legal_aid_pc,
"paralegal_density_per_100k": paralegal_dens,
"cost_pct_monthly_income": cost_pct,
"bribery_rate_pct": bribery,
"trust_in_courts_pct": trust,
"gender_access_ratio": gender_ratio,
"customary_justice_use_pct": customary_use,
"court_contact_rate_pct": contact_rate,
"wjp_rule_of_law_score": wjp,
"access_score": access_score,
"access_level": access_level,
})
# --- Print summary ---
print(f"\n{'='*70}")
print(f"AFRICAN JUDICIAL ACCESS INDICATORS — GENERATION SUMMARY")
print(f"Scenario: {scenario_name} | N: {n:,} | Seed: {seed}")
print(f"{'='*70}")
print(f"\nCountry distribution:")
print(df["country"].value_counts().to_string())
print(f"\nRegion type distribution:")
print(df["region_type"].value_counts(normalize=True).mul(100).round(1).to_string())
print(f"\nAccess level distribution:")
print(df["access_level"].value_counts(normalize=True).mul(100).round(1).to_string())
print(f"\nKey statistics:")
for col in ["lawyer_density_per_100k", "distance_to_court_km", "travel_time_hours",
"legal_aid_coverage_pct", "cost_pct_monthly_income", "bribery_rate_pct",
"trust_in_courts_pct", "gender_access_ratio", "court_contact_rate_pct",
"access_score"]:
print(f" {col}: mean={df[col].mean():.2f}, sd={df[col].std():.2f}, "
f"min={df[col].min():.2f}, max={df[col].max():.2f}")
print(f"{'='*70}\n")
return df
# ============================================================================
# SECTION 4: CLI ENTRY POINT
# ============================================================================
def main():
parser = argparse.ArgumentParser(
description="Generate synthetic African judicial access indicators dataset"
)
parser.add_argument("--scenario", choices=list(SCENARIOS.keys()), default="baseline")
parser.add_argument("--n", type=int, default=10000)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--output", type=str, default=None)
args = parser.parse_args()
df = generate_judicial_access_data(args.scenario, args.n, args.seed)
if args.output is None:
script_dir = os.path.dirname(os.path.abspath(__file__))
output_dir = os.path.join(script_dir, "data")
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, f"{args.scenario}.csv")
else:
output_path = args.output
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
df.to_csv(output_path, index=False)
print(f"Dataset saved to: {output_path}")
print(f"Shape: {df.shape}")
if __name__ == "__main__":
main()