import pandas as pd
import numpy as np
import random
import time
from faker import Faker
from dataclasses import dataclass
from typing import List, Dict, Callable, Any
from collections import defaultdict
# ==========================================
# 1. CONFIGURATION & DATA STRUCTURES
# ==========================================
fake = Faker()
@dataclass
class User:
id: str
age: int
income: int
gender: str
ethnicity: str
zip_code: str
tenure_days: int
total_spend: float
is_vip: bool
@dataclass
class Segment:
name: str
logic: Callable[[User], bool] # A function returning True/False
@dataclass
class Campaign:
name: str
eligible_segments: List[str]
priority: int # Higher number = higher priority if conflicts exist
# ==========================================
# 2. SYNTHETIC DATA FACTORY
# ==========================================
class PopulationGenerator:
def __init__(self, seed=42):
np.random.seed(seed)
def generate_users(self, n=1000) -> List[User]:
users = []
for _ in range(n):
# Introduce correlations (e.g., Age correlates with Income)
age = np.random.randint(18, 80)
base_income = 30000 + (age * 1000) + np.random.randint(-10000, 20000)
# Introduce potential bias sources (e.g., VIP status correlates with specific demographics)
# This creates "latent bias" for the auditor to find.
is_vip = np.random.choice([True, False], p=[0.1, 0.9])
if is_vip:
# Skew VIPs towards higher income
base_income += 50000
users.append(User(
id=fake.uuid4(),
age=age,
income=int(max(20000, base_income)),
gender=np.random.choice(['Male', 'Female', 'Non-Binary'], p=[0.45, 0.45, 0.10]),
ethnicity=np.random.choice(['Group A', 'Group B', 'Group C', 'Group D']),
zip_code=fake.zipcode(),
tenure_days=np.random.randint(0, 1000),
total_spend=round(np.random.exponential(scale=500), 2),
is_vip=is_vip
))
return users
# ==========================================
# 3. ELIGIBILITY ENGINE (The "Brain")
# ==========================================
class EligibilityEngine:
def __init__(self, segments: List[Segment], campaigns: List[Campaign]):
self.segments = {s.name: s for s in segments}
self.campaigns = sorted(campaigns, key=lambda x: x.priority, reverse=True)
def evaluate_user(self, user: User) -> Dict[str, Any]:
"""
Evaluates a user against all segments and assigns the highest priority campaign.
Returns a dictionary detailing the decision path.
"""
matched_segments = []
# 1. Check Segment Membership
for seg_name, seg in self.segments.items():
try:
if seg.logic(user):
matched_segments.append(seg_name)
except Exception as e:
# Stress test handling: Logic should not crash on bad data
matched_segments.append(f"ERROR_IN_{seg_name}")
# 2. Check Campaign Eligibility
assigned_campaign = None
for camp in self.campaigns:
# Check if user matches ANY of the required segments for this campaign
# Logic: Intersection of matched_segments and campaign_requirements is not empty
if set(matched_segments) & set(camp.eligible_segments):
assigned_campaign = camp.name
break # Stop after highest priority match
return {
"user_id": user.id,
"matched_segments": matched_segments,
"assigned_campaign": assigned_campaign or "CONTROL_GROUP",
"user_age": user.age,
"user_ethnicity": user.ethnicity,
"user_gender": user.gender,
"user_income": user.income
}
# ==========================================
# 4. SIMULATION LAB & FAIRNESS AUDITOR
# ==========================================
class SimulationLab:
def __init__(self, engine: EligibilityEngine):
self.engine = engine
self.results = pd.DataFrame()
def run_simulation(self, users: List[User]):
print(f"--- Running Simulation on {len(users)} Users ---")
start_time = time.time()
decisions = []
for user in users:
decision = self.engine.evaluate_user(user)
decisions.append(decision)
self.results = pd.DataFrame(decisions)
duration = time.time() - start_time
print(f"--- Completed in {duration:.4f} seconds ---")
def audit_fairness(self, protected_attr: str, positive_outcome: str):
"""
Performs a Disparate Impact Analysis.
Calculates the 'Adverse Impact Ratio' (AIR).
AIR < 0.80 is generally considered evidence of adverse impact (the 80% rule).
"""
print(f"\n=== FAIRNESS AUDIT: {protected_attr} ===")
# Filter out control group if necessary, or treat specific campaign as 'positive'
df = self.results.copy()
# Create a binary 'Selected' column
df['selected'] = (df['assigned_campaign'] == positive_outcome).astype(int)
# Group by protected attribute
group_stats = df.groupby(protected_attr).agg(
total_count=('selected', 'count'),
selection_count=('selected', 'sum')
).reset_index()
group_stats['selection_rate'] = group_stats['selection_count'] / group_stats['total_count']
# Find the group with the highest selection rate (Reference Group)
reference_rate = group_stats['selection_rate'].max()
print(f"Target Positive Outcome: '{positive_outcome}'")
print("-" * 50)
alerts = []
for _, row in group_stats.iterrows():
air = row['selection_rate'] / reference_rate if reference_rate > 0 else 0
status = "OK" if air >= 0.80 else "⚠️ ALERT"
print(f"Group: {row[protected_attr]:<15} | Rate: {row['selection_rate']:.2%} | AIR: {air:.2f} | Status: {status}")
if air < 0.80:
alerts.append(row[protected_attr])
if alerts:
print(f"\nBIAS DETECTED: Groups {alerts} are under-served relative to the reference group.")
else:
print("\nAUDIT PASSED: No significant disparate impact detected (AIR > 0.80 for all groups).")
# ==========================================
# 5. EXECUTION: STRESS TESTING
# ==========================================
if __name__ == "__main__":
# A. Define Logic Rules (Simulating business logic)
def logic_high_value(u: User):
return u.total_spend > 1000 or u.is_vip
def logic_risk_segment(u: User):
# Arbitrary complex logic
return u.tenure_days < 30 and u.total_spend > 500
def logic_bias_towards_group_a(u: User):
# A rule that looks neutral but might interact with data correlations
# Example: Preferring users with income > 80k
return u.income > 80000
# B. Setup Segments and Campaigns
segments = [
Segment("High_Value_Customers", logic_high_value),
Segment("New_Risky_Spenders", logic_risk_segment),
Segment("Premium_Income", logic_bias_towards_group_a)
]
campaigns = [
Campaign(name="VIP_Discount", eligible_segments=["High_Value_Customers"], priority=10),
Campaign(name="New_User_Coupon", eligible_segments=["New_Risky_Spenders"], priority=5),
Campaign(name="Premium_Card_Offer", eligible_segments=["Premium_Income"], priority=2)
]
engine = EligibilityEngine(segments, campaigns)
lab = SimulationLab(engine)
# C. Generate Data
gen = PopulationGenerator()
population = gen.generate_users(n=50000)
# D. Run Lab
lab.run_simulation(population)
# E. Audits
# Audit 1: Gender fairness for 'VIP_Discount'
lab.audit_fairness(protected_attr="user_gender", positive_outcome="VIP_Discount")
# Audit 2: Ethnicity fairness for 'Premium_Card_Offer'
# This is likely to show bias if income is correlated with ethnicity in the synthetic data
# (In the generator, we didn't strictly correlate ethnicity with income, but let's assume we did or rely on randomness)
lab.audit_fairness(protected_attr="user_ethnicity", positive_outcome="Premium_Card_Offer")