StrategyForge's picture
Claude Opus 4.6
feat: add model results data, NOVA service, and updated simulation/services
b6b1511
Raw History Blame Contribute Delete
39.4 kB
"""
Integrated Simulation & Optimization Engine
============================================
Ported from FastAPI Simulator and extended with:
- Media channel allocation (TV, Digital, Paid Search, Social, etc.)
- Trade promo mechanics (Off-invoice, Bill-back, Scan-down, etc.)
- 3-bucket optimization: Media + Consumer Promo + Trade
Core promo simulation follows the 10-step algorithm:
1. GET baseline data
2. CHECK if promo event exists this week
3. APPLY promo-mechanic multiplier
4. APPLY feature multiplier
5. APPLY display multiplier
6. APPLY synergy factor
7. CALCULATE gross incremental units
8. APPLY cannibalization
9. DEDUCT pantry loading
10. CALCULATE financials
Media simulation uses Hill saturation curves.
Trade simulation uses trade-specific uplift parameters.
"""
from __future__ import annotations
import math
import json
from datetime import date, timedelta
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
try:
import pulp
PULP_AVAILABLE = True
except ImportError:
PULP_AVAILABLE = False
from app_pkg.services.simulator_data_loader import sim_data_loader
# ─────────────────────────────────────────────────────────────────
# Offer spec -> discount depth mapping
# ─────────────────────────────────────────────────────────────────
OFFER_DISCOUNT_MAP = {
"100% OFF on 2nd": 0.50, "75% OFF on 2nd": 0.375,
"50% OFF on 2nd": 0.25, "25% OFF on 2nd": 0.125,
"5% OFF": 0.05, "10% OFF": 0.10, "15% OFF": 0.15,
"20% OFF": 0.20, "25% OFF": 0.25, "30% OFF": 0.30,
"Buy 2 Save $5": 0.12, "Buy 3 Save $10": 0.14,
"3 for $10": 0.15, "2 for $8": 0.10,
"$1 OFF": 0.10, "$2 OFF": 0.18, "$3 OFF": 0.25, "$5 OFF": 0.35,
}
_UPLIFT_COL_MAP = {
"100% OFF on 2nd": "BOGO_100", "75% OFF on 2nd": "BOGO_75",
"50% OFF on 2nd": "BOGO_50", "25% OFF on 2nd": "BOGO_25",
"5% OFF": "TPR_5", "10% OFF": "TPR_10", "15% OFF": "TPR_15",
"20% OFF": "TPR_20", "25% OFF": "TPR_25", "30% OFF": "TPR_30",
"Buy 2 Save $5": "multiBuy_2for", "Buy 3 Save $10": "multiBuy_3for",
"3 for $10": "multiBuy_3for", "2 for $8": "multiBuy_2for",
"$1 OFF": "dollarOff_1", "$2 OFF": "dollarOff_2",
"$3 OFF": "dollarOff_3", "$5 OFF": "dollarOff_3",
}
_FEATURE_COL_MAP = {
"FEATURE": "frontPage", "NO_FEATURE": "noFeature",
"frontPage": "frontPage", "middlePage": "middlePage", "backPage": "backPage",
}
_DISPLAY_COL_MAP = {
"disp_w_feat": "eventDisplay", "disp_wo_feat": "gondola",
"event": "eventDisplay", "gondola": "gondola",
"stack": "stack", "noDisplay": "noDisplay",
}
# Media channel Hill curve defaults
MEDIA_CHANNEL_DEFAULTS = {
'TV': {'K': 5000000, 'S': 800000, 'n': 2.0, 'color': '#3987e5'},
'Digital Display': {'K': 3500000, 'S': 400000, 'n': 1.8, 'color': '#d95926'},
'Paid Search': {'K': 4000000, 'S': 300000, 'n': 1.6, 'color': '#199e70'},
'Social Media': {'K': 3000000, 'S': 350000, 'n': 1.7, 'color': '#7c6cc4'},
'Radio': {'K': 1500000, 'S': 200000, 'n': 2.2, 'color': '#c98500'},
'Print': {'K': 1200000, 'S': 250000, 'n': 2.5, 'color': '#47a1b8'},
'OOH': {'K': 1800000, 'S': 300000, 'n': 2.3, 'color': '#d55181'},
'Programmatic': {'K': 2500000, 'S': 200000, 'n': 1.5, 'color': '#e87ba4'},
}
# Trade mechanic effectiveness multipliers
TRADE_MECHANIC_EFFECTIVENESS = {
'Off-invoice': {'lift_mult': 1.25, 'roi_mult': 1.8, 'color': '#3987e5'},
'Bill-back': {'lift_mult': 1.15, 'roi_mult': 2.1, 'color': '#d95926'},
'Scan-down': {'lift_mult': 1.35, 'roi_mult': 1.6, 'color': '#199e70'},
'Display allowance': {'lift_mult': 1.45, 'roi_mult': 1.4, 'color': '#c98500'},
'Slotting fee': {'lift_mult': 1.10, 'roi_mult': 1.2, 'color': '#ef4444'},
'Co-op advertising': {'lift_mult': 1.55, 'roi_mult': 1.9, 'color': '#7c6cc4'},
'Volume rebate': {'lift_mult': 1.20, 'roi_mult': 2.3, 'color': '#47a1b8'},
}
MECHANICS_CATALOGUE = [
("BOGO", "100% OFF on 2nd", "BOGO_100"),
("BOGO", "75% OFF on 2nd", "BOGO_75"),
("BOGO", "50% OFF on 2nd", "BOGO_50"),
("TPR", "10% OFF", "TPR_10"),
("TPR", "20% OFF", "TPR_20"),
("TPR", "30% OFF", "TPR_30"),
("Multi-Buy", "Buy 2 Save $5", "multiBuy_2for"),
("Multi-Buy", "Buy 3 Save $10", "multiBuy_3for"),
("Dollar Off", "$2 OFF", "dollarOff_2"),
("Dollar Off", "$3 OFF", "dollarOff_3"),
]
FEATURES_CATALOGUE = [
("frontPage", "frontPage"),
("middlePage", "middlePage"),
("backPage", "backPage"),
("noFeature", "noFeature"),
]
DISPLAYS_CATALOGUE = [
("eventDisplay", "eventDisplay"),
("gondola", "gondola"),
("stack", "stack"),
("noDisplay", "noDisplay"),
]
# ─────────────────────────────────────────────────────────────────
# Hill saturation model
# ─────────────────────────────────────────────────────────────────
def _hill(x, K, S, n):
x = np.maximum(x, 0)
return K * np.power(x, n) / (np.power(S, n) + np.power(x, n))
def _hill_marginal(x, K, S, n):
x = np.maximum(x, 1e-6)
num = K * n * np.power(S, n) * np.power(x, n - 1)
den = np.power(np.power(S, n) + np.power(x, n), 2)
return num / den
# ─────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────
def _to_date(val) -> date:
if isinstance(val, date):
return val
if isinstance(val, str):
return date.fromisoformat(val[:10])
return date.today()
def _weeks_between(start: date, end: date) -> List[date]:
weeks = []
current = start - timedelta(days=start.weekday())
end_monday = end - timedelta(days=end.weekday())
while current <= end_monday:
weeks.append(current)
current += timedelta(weeks=1)
return weeks
def _find_event_for_week(events, ppg_id, week_date):
for ev in events:
if ev.get("productFamily") != ppg_id:
continue
ev_start = _to_date(ev["startDate"])
ev_end = _to_date(ev["endDate"])
if ev_start <= week_date <= ev_end:
return ev
return None
def _get_uplift_multiplier(uplift_row, offer_spec):
col = _UPLIFT_COL_MAP.get(offer_spec)
if col and uplift_row is not None and col in uplift_row.index:
return float(uplift_row[col])
return 1.0
def _get_feature_multiplier(uplift_row, feature):
col = _FEATURE_COL_MAP.get(feature, "noFeature")
if uplift_row is not None and col in uplift_row.index:
return float(uplift_row[col])
return 1.0
def _get_display_multiplier(uplift_row, display):
col = _DISPLAY_COL_MAP.get(display, "noDisplay")
if uplift_row is not None and col in uplift_row.index:
return float(uplift_row[col])
return 1.0
def _zero_metrics():
return {
"totalUnitsSold": 0.0, "grossTotalSales": 0.0, "promoCIW": 0.0,
"netTotalSales": 0.0, "costOfGoodsSold": 0.0, "grossProfit": 0.0,
"iGTS": 0.0, "iNTS": 0.0, "iCOGS": 0.0, "iGP": 0.0,
"totalInvestment": 0.0,
"baselineUnits": 0.0, "baselineGTS": 0.0,
"baselineNTS": 0.0, "baselineGP": 0.0,
}
def _add_metrics(target, source):
for k, v in source.items():
target[k] = target.get(k, 0.0) + v
def _fmt_currency(v):
if abs(v) >= 1e6:
return f'${v/1e6:,.1f}M'
if abs(v) >= 1e3:
return f'${v/1e3:,.0f}K'
return f'${v:,.0f}'
# ─────────────────────────────────────────────────────────────────
# PROMO SIMULATION ENGINE (10-step)
# ─────────────────────────────────────────────────────────────────
def run_promo_simulation(scope, events):
"""
10-step promo simulation for consumer promo events.
Returns financial performance, per-PPG summary, weekly detail, and calendar.
"""
retailer = scope.get("retailer", "Shoppers Drug Mart")
category = scope.get("category", "Foods")
brand = scope.get("brand", "Brand 1")
start_date = pd.Timestamp(_to_date(scope["timePeriod"]["start"]))
end_date = pd.Timestamp(_to_date(scope["timePeriod"]["end"]))
ppg_ids_from_events = list({ev["productFamily"] for ev in events})
ppg_ids_from_config = sim_data_loader.get_all_ppg_ids(category, brand)
all_ppg_ids = sorted(set(ppg_ids_from_events + ppg_ids_from_config)) or ppg_ids_from_events
baseline_by_ppg = sim_data_loader.get_all_ppgs_baseline(retailer, start_date, end_date)
if not baseline_by_ppg:
return {"error": f"No baseline data for {retailer} in date range"}
all_ppg_ids = [p for p in all_ppg_ids if p in baseline_by_ppg]
# Build promoted PPGs per week for cannibalization
promoted_ppgs_by_week = {}
for ev in events:
ev_start = _to_date(ev["startDate"])
ev_end = _to_date(ev["endDate"])
for w in _weeks_between(ev_start, ev_end):
promoted_ppgs_by_week.setdefault(w, []).append(ev["productFamily"])
weekly_output = []
ppg_aggregates = {}
total_planned = _zero_metrics()
total_simulated = _zero_metrics()
for ppg_id in all_ppg_ids:
baseline_df = baseline_by_ppg.get(ppg_id, pd.DataFrame())
if baseline_df.empty:
continue
uplift_row = sim_data_loader.get_uplift_row(ppg_id, retailer)
costs_row = sim_data_loader.get_costs_row(ppg_id, retailer)
ppg_agg = _zero_metrics()
for _, row in baseline_df.iterrows():
week_date = row["weekStartDate"].date() if hasattr(row["weekStartDate"], 'date') else row["weekStartDate"]
base_units = float(row["baselineUnits"])
base_gts = float(row["baselineGTS"])
base_nts = float(row.get("baselineNTS", base_gts))
regular_price = float(row["regularPrice"])
unit_cogs = float(row["unitCOGS"])
event = _find_event_for_week(events, ppg_id, week_date)
if event is None:
sim_units = base_units
promo_price = regular_price
discount_depth = 0.0
gross_incremental = 0.0
net_incremental = 0.0
else:
offer_spec = event.get("offerSpec", "")
feature = event.get("feature", "NO_FEATURE")
display = event.get("display", "disp_wo_feat")
promo_mult = _get_uplift_multiplier(uplift_row, offer_spec) if uplift_row is not None else 1.0
feat_mult = _get_feature_multiplier(uplift_row, feature) if uplift_row is not None else 1.0
disp_mult = _get_display_multiplier(uplift_row, display) if uplift_row is not None else 1.0
has_feature = feature != "NO_FEATURE"
has_display = display != "noDisplay"
synergy = 1.0
if has_feature and has_display and uplift_row is not None:
synergy = 1.0 + float(uplift_row.get("featureDisplaySynergy", 0.0))
gross_lift = promo_mult * feat_mult * disp_mult * synergy
gross_incremental = base_units * (gross_lift - 1.0)
# Cannibalization
other_promoted = [p for p in promoted_ppgs_by_week.get(week_date, []) if p != ppg_id]
cannibal_units = 0.0
for src in other_promoted:
factor = sim_data_loader.get_cannibalization_factor(src, ppg_id, retailer)
if factor < 1.0:
cannibal_units += gross_incremental * (1.0 - factor)
gross_incremental = max(0.0, gross_incremental - cannibal_units)
# Pantry loading
pantry_rate = float(uplift_row.get("pantryLoadingRate", 0.0)) if uplift_row is not None else 0.0
net_incremental = max(0.0, gross_incremental * (1.0 - pantry_rate))
sim_units = base_units + net_incremental
discount_depth = OFFER_DISCOUNT_MAP.get(offer_spec, 0.0)
if event.get("promoMechanic") == "Dollar Off":
dollar_vals = {"$1 OFF": 1.0, "$2 OFF": 2.0, "$3 OFF": 3.0, "$5 OFF": 5.0}
dollar_amt = dollar_vals.get(offer_spec, 1.0)
discount_depth = min(dollar_amt / regular_price, 0.50)
promo_price = regular_price * (1.0 - discount_depth)
# Financials
sim_gts = sim_units * regular_price
promo_ciw = max(0.0, (regular_price - promo_price) * sim_units) if event else 0.0
sim_nts = sim_gts - promo_ciw
sim_cogs = sim_units * unit_cogs
sim_gp = sim_nts - sim_cogs
base_gp = base_nts - (base_units * unit_cogs)
feature_cost = 0.0
display_cost = 0.0
if event and costs_row is not None:
feat = event.get("feature", "NO_FEATURE")
disp = event.get("display", "disp_wo_feat")
if feat in ("FEATURE", "frontPage"):
feature_cost = float(costs_row.get("featureFrontPage", 0))
elif feat == "middlePage":
feature_cost = float(costs_row.get("featureMiddlePage", 0))
elif feat == "backPage":
feature_cost = float(costs_row.get("featureBackPage", 0))
if "event" in disp:
display_cost = float(costs_row.get("displayEvent", 0))
elif "gondola" in disp:
display_cost = float(costs_row.get("displayGondola", 0))
elif "stack" in disp:
display_cost = float(costs_row.get("displayStack", 0))
total_investment = promo_ciw + feature_cost + display_cost
_add_metrics(ppg_agg, {
"totalUnitsSold": sim_units, "grossTotalSales": sim_gts,
"promoCIW": promo_ciw, "netTotalSales": sim_nts,
"costOfGoodsSold": sim_cogs, "grossProfit": sim_gp,
"iGTS": sim_gts - base_gts, "iNTS": sim_nts - base_nts,
"iCOGS": sim_cogs - base_units * unit_cogs, "iGP": sim_gp - base_gp,
"totalInvestment": total_investment,
"baselineUnits": base_units, "baselineGTS": base_gts,
"baselineNTS": base_nts, "baselineGP": base_gp,
})
weekly_output.append({
"ppgId": ppg_id,
"weekNumber": int(row.get("weekNumber", 0)),
"startDate": week_date.isoformat() if hasattr(week_date, 'isoformat') else str(week_date),
"baseUnits": round(base_units),
"simUnits": round(sim_units),
"incrementalUnits": round(net_incremental if event else 0),
"liftPct": round((sim_units - base_units) / base_units * 100, 1) if base_units > 0 else 0,
"baseGTS": round(base_gts, 2),
"simGTS": round(sim_gts, 2),
"simNTS": round(sim_nts, 2),
"simGP": round(sim_gp, 2),
"iGP": round(sim_gp - base_gp, 2),
"hasPromo": event is not None,
})
# Per-PPG summary
agg = ppg_agg
agg_inv = agg.get("totalInvestment", 0)
agg_base = agg.get("baselineUnits", 1)
ppg_roi = agg["iGP"] / agg_inv if agg_inv > 0 else 0
ppg_lift = (agg["totalUnitsSold"] - agg_base) / agg_base * 100 if agg_base > 0 else 0
ppg_aggregates[ppg_id] = {
"productFamily": ppg_id, "category": category, "brand": brand,
"totalUnits": round(agg["totalUnitsSold"]),
"baselineUnits": round(agg["baselineUnits"]),
"incrementalUnits": round(agg["totalUnitsSold"] - agg["baselineUnits"]),
"liftPct": round(ppg_lift, 1),
"iGTS": round(agg["iGTS"], 2), "iNTS": round(agg["iNTS"], 2),
"iGP": round(agg["iGP"], 2), "roi": round(ppg_roi, 2),
"totalInvestment": round(agg["totalInvestment"], 2),
}
_add_metrics(total_simulated, {
"totalUnitsSold": agg["totalUnitsSold"], "grossTotalSales": agg["grossTotalSales"],
"promoCIW": agg["promoCIW"], "netTotalSales": agg["netTotalSales"],
"costOfGoodsSold": agg["costOfGoodsSold"], "grossProfit": agg["grossProfit"],
})
_add_metrics(total_planned, {
"totalUnitsSold": agg["baselineUnits"], "grossTotalSales": agg["baselineGTS"],
"netTotalSales": agg["baselineNTS"], "grossProfit": agg["baselineGP"],
})
# Build calendar entries
calendar = []
for ev in events:
calendar.append({
"productFamily": ev["productFamily"],
"startDate": _to_date(ev["startDate"]).isoformat(),
"endDate": _to_date(ev["endDate"]).isoformat(),
"promoMechanic": ev.get("promoMechanic", "TPR"),
"offerSpec": ev.get("offerSpec", ""),
"feature": ev.get("feature", "NO_FEATURE"),
"display": ev.get("display", "noDisplay"),
"discountDepth": OFFER_DISCOUNT_MAP.get(ev.get("offerSpec", ""), 0),
})
return {
"financialPerformance": {
"baseline": {
"totalUnits": round(total_planned["totalUnitsSold"]),
"grossSales": round(total_planned["grossTotalSales"], 2),
"netSales": round(total_planned["netTotalSales"], 2),
"grossProfit": round(total_planned["grossProfit"], 2),
},
"simulated": {
"totalUnits": round(total_simulated["totalUnitsSold"]),
"grossSales": round(total_simulated["grossTotalSales"], 2),
"netSales": round(total_simulated["netTotalSales"], 2),
"grossProfit": round(total_simulated["grossProfit"], 2),
"promoCIW": round(total_simulated["promoCIW"], 2),
},
},
"ppgSummary": list(ppg_aggregates.values()),
"weeklyDetail": weekly_output,
"promoCalendar": calendar,
"ppgIds": all_ppg_ids,
}
# ─────────────────────────────────────────────────────────────────
# MEDIA SIMULATION ENGINE (Hill saturation)
# ─────────────────────────────────────────────────────────────────
def run_media_simulation(media_allocations, mmm_media_df=None):
"""
Simulate media channel impact using Hill saturation curves.
media_allocations: {channel_name: spend_amount}
Returns per-channel response and total impact.
"""
results = {}
total_spend = 0
total_response = 0
for channel, spend in media_allocations.items():
params = MEDIA_CHANNEL_DEFAULTS.get(channel, {'K': 2000000, 'S': 300000, 'n': 2.0})
# The model-results contract is the primary calibration source. Legacy
# defaults remain only for a channel that has no MMM result artifact.
fitted = sim_data_loader.get_media_response_params(channel)
if fitted:
params = {**params, **fitted}
# If we have MMM data, calibrate K and S
if not fitted and mmm_media_df is not None and len(mmm_media_df) > 0:
ch_data = mmm_media_df[mmm_media_df['channel'] == channel] if 'channel' in mmm_media_df.columns else pd.DataFrame()
if len(ch_data) > 0:
hist_spend = float(ch_data['spend'].sum())
if hist_spend > 0:
params = dict(params)
params['S'] = hist_spend * 0.9
params['K'] = hist_spend * 4.0
response = float(_hill(spend, params['K'], params['S'], params['n']))
marginal = float(_hill_marginal(spend, params['K'], params['S'], params['n']))
roas = response / spend if spend > 0 else 0
saturation_pct = response / params['K'] * 100 if params['K'] > 0 else 0
results[channel] = {
'spend': spend,
'response': round(response, 2),
'roas': round(roas, 3),
'marginalReturn': round(marginal, 4),
'saturationPct': round(saturation_pct, 1),
'color': params.get('color', '#3b82f6'),
}
total_spend += spend
total_response += response
return {
'channels': results,
'totalSpend': round(total_spend, 2),
'totalResponse': round(total_response, 2),
'overallROAS': round(total_response / total_spend, 3) if total_spend > 0 else 0,
}
# ─────────────────────────────────────────────────────────────────
# TRADE SIMULATION ENGINE
# ─────────────────────────────────────────────────────────────────
def run_trade_simulation(trade_events, baseline_revenue=10000000):
"""
Simulate trade promo events.
trade_events: list of {type, spend, retailer, startDate, endDate, product}
"""
results = []
total_spend = 0
total_incremental = 0
for ev in trade_events:
ttype = ev.get('type', 'Off-invoice')
spend = float(ev.get('spend', 0))
params = TRADE_MECHANIC_EFFECTIVENESS.get(ttype, {'lift_mult': 1.2, 'roi_mult': 1.5})
# Calculate incremental impact
incremental_rev = spend * params['roi_mult']
volume_lift = params['lift_mult'] - 1.0
roi = (incremental_rev - spend) / spend if spend > 0 else 0
results.append({
'eventName': ev.get('name', f'Trade-{len(results)+1}'),
'type': ttype,
'retailer': ev.get('retailer', 'All'),
'spend': round(spend, 2),
'incrementalRevenue': round(incremental_rev, 2),
'volumeLiftPct': round(volume_lift * 100, 1),
'roi': round(roi, 2),
'startDate': ev.get('startDate', ''),
'endDate': ev.get('endDate', ''),
'color': params.get('color', '#f59e0b'),
})
total_spend += spend
total_incremental += incremental_rev
return {
'events': results,
'totalSpend': round(total_spend, 2),
'totalIncrementalRevenue': round(total_incremental, 2),
'overallROI': round((total_incremental - total_spend) / total_spend, 2) if total_spend > 0 else 0,
}
# ─────────────────────────────────────────────────────────────────
# INTEGRATED 3-BUCKET SIMULATION
# ─────────────────────────────────────────────────────────────────
def run_integrated_simulation(scope, promo_events, media_allocations, trade_events, mmm_media_df=None):
"""
Run combined simulation across all 3 buckets.
Returns unified results with per-bucket breakdown.
"""
# Promo simulation
promo_result = None
if promo_events:
promo_result = run_promo_simulation(scope, promo_events)
# Media simulation
media_result = None
if media_allocations:
media_result = run_media_simulation(media_allocations, mmm_media_df)
# Trade simulation
trade_result = None
if trade_events:
baseline_rev = 0
if promo_result:
baseline_rev = promo_result["financialPerformance"]["baseline"]["grossSales"]
trade_result = run_trade_simulation(trade_events, baseline_rev)
# Combine results
baseline_revenue = 0
simulated_revenue = 0
total_spend = 0
if promo_result and "error" not in promo_result:
baseline_revenue += promo_result["financialPerformance"]["baseline"]["grossSales"]
simulated_revenue += promo_result["financialPerformance"]["simulated"]["grossSales"]
total_spend += promo_result["financialPerformance"]["simulated"].get("promoCIW", 0)
if media_result:
simulated_revenue += media_result["totalResponse"]
total_spend += media_result["totalSpend"]
if trade_result:
simulated_revenue += trade_result["totalIncrementalRevenue"]
total_spend += trade_result["totalSpend"]
return {
"promoResult": promo_result,
"mediaResult": media_result,
"tradeResult": trade_result,
"combined": {
"baselineRevenue": round(baseline_revenue, 2),
"simulatedRevenue": round(simulated_revenue, 2),
"totalSpend": round(total_spend, 2),
"incrementalRevenue": round(simulated_revenue - baseline_revenue, 2),
"overallROAS": round(simulated_revenue / total_spend, 3) if total_spend > 0 else 0,
}
}
# ─────────────────────────────────────────────────────────────────
# 3-BUCKET OPTIMIZATION
# ─────────────────────────────────────────────────────────────────
def run_3bucket_optimization(scope, total_budget, constraints=None, mmm_media_df=None):
"""
Optimize allocation across Media, Consumer Promo, and Trade buckets.
Uses marginal return equalization across all channels/mechanics.
"""
constraints = constraints or {}
retailer = scope.get("retailer", "Shoppers Drug Mart")
category = scope.get("category", "Foods")
brand = scope.get("brand", "Brand 1")
# Build media channels with Hill params
media_channels = {}
if mmm_media_df is not None and len(mmm_media_df) > 0:
for ch in mmm_media_df['channel'].unique():
ch_spend = float(mmm_media_df[mmm_media_df['channel'] == ch]['spend'].sum())
params = MEDIA_CHANNEL_DEFAULTS.get(ch, {'K': 2000000, 'S': 300000, 'n': 2.0, 'color': '#3b82f6'})
params = dict(params)
fitted = sim_data_loader.get_media_response_params(ch)
if fitted:
params.update(fitted)
else:
params['S'] = max(ch_spend * 0.9, params['S'] * 0.5)
params['K'] = max(ch_spend * 4.0, params['K'] * 0.8)
media_channels[ch] = {'spend': ch_spend, **params}
else:
for ch, params in MEDIA_CHANNEL_DEFAULTS.items():
if ch in ('TV', 'Digital Display', 'Paid Search', 'Social Media'):
media_channels[ch] = {'spend': 200000, **params}
# Build trade mechanics with effectiveness
trade_mechanics = {}
for ttype, params in TRADE_MECHANIC_EFFECTIVENESS.items():
trade_mechanics[ttype] = {'spend': total_budget * 0.02, **params}
# Build promo mechanics with average effectiveness
promo_effective = {}
avg_uplift = 1.3
for mech_name, offer, col in MECHANICS_CATALOGUE[:5]: # Use top 5 mechanics
promo_effective[f"Promo-{offer}"] = {
'spend': total_budget * 0.02,
'roi_mult': avg_uplift + np.random.random() * 0.5,
}
# Marginal return optimization across all channels
all_channels = {}
for ch, data in media_channels.items():
all_channels[f"media_{ch}"] = {
'bucket': 'Media', 'name': ch,
'spend': data['spend'], 'K': data['K'], 'S': data['S'], 'n': data['n'],
'type': 'hill', 'color': data.get('color', '#3b82f6'),
}
for ttype, data in trade_mechanics.items():
K_trade = data['spend'] * data['roi_mult'] * 3
all_channels[f"trade_{ttype}"] = {
'bucket': 'Trade', 'name': ttype,
'spend': data['spend'], 'K': K_trade, 'S': data['spend'] * 1.5,
'n': 1.8, 'type': 'hill', 'color': data.get('color', '#f59e0b'),
}
# Optimize using marginal return equalization
n_channels = len(all_channels)
if n_channels == 0:
return {"error": "No channels to optimize"}
channel_keys = list(all_channels.keys())
current_total = sum(all_channels[k]['spend'] for k in channel_keys)
# Initialize allocations proportionally
allocations = {}
for k in channel_keys:
share = all_channels[k]['spend'] / current_total if current_total > 0 else 1 / n_channels
allocations[k] = total_budget * share
# Apply constraints
for k in channel_keys:
ch_min = constraints.get(k, {}).get('min', 0)
ch_max = constraints.get(k, {}).get('max', total_budget)
allocations[k] = max(ch_min, min(ch_max, allocations[k]))
# Iterative optimization
for _ in range(300):
marginals = {}
for k in channel_keys:
ch = all_channels[k]
marginals[k] = float(_hill_marginal(allocations[k], ch['K'], ch['S'], ch['n']))
sorted_ch = sorted(channel_keys, key=lambda c: marginals[c], reverse=True)
best, worst = sorted_ch[0], sorted_ch[-1]
if marginals[best] <= marginals[worst] * 1.05:
break
step = total_budget * 0.003
ch_min_w = constraints.get(worst, {}).get('min', 0)
ch_max_b = constraints.get(best, {}).get('max', total_budget)
actual_step = min(step, allocations[worst] - ch_min_w, ch_max_b - allocations[best])
if actual_step <= 0:
break
allocations[worst] -= actual_step
allocations[best] += actual_step
# Build results
results_by_bucket = {'Media': [], 'Trade': []}
for k in channel_keys:
ch = all_channels[k]
cur_spend = ch['spend']
opt_spend = allocations[k]
cur_response = float(_hill(cur_spend, ch['K'], ch['S'], ch['n']))
opt_response = float(_hill(opt_spend, ch['K'], ch['S'], ch['n']))
entry = {
'name': ch['name'],
'currentSpend': round(cur_spend, 2),
'optimizedSpend': round(opt_spend, 2),
'changePct': round((opt_spend - cur_spend) / cur_spend * 100, 1) if cur_spend > 0 else 0,
'currentResponse': round(cur_response, 2),
'optimizedResponse': round(opt_response, 2),
'incrementalResponse': round(opt_response - cur_response, 2),
'currentROAS': round(cur_response / cur_spend, 3) if cur_spend > 0 else 0,
'optimizedROAS': round(opt_response / opt_spend, 3) if opt_spend > 0 else 0,
'color': ch.get('color', '#3b82f6'),
}
results_by_bucket[ch['bucket']].append(entry)
total_current_response = sum(
float(_hill(all_channels[k]['spend'], all_channels[k]['K'],
all_channels[k]['S'], all_channels[k]['n']))
for k in channel_keys
)
total_optimized_response = sum(
float(_hill(allocations[k], all_channels[k]['K'],
all_channels[k]['S'], all_channels[k]['n']))
for k in channel_keys
)
return {
"buckets": results_by_bucket,
"summary": {
"totalBudget": round(total_budget, 2),
"currentTotalResponse": round(total_current_response, 2),
"optimizedTotalResponse": round(total_optimized_response, 2),
"incrementalResponse": round(total_optimized_response - total_current_response, 2),
"upliftPct": round((total_optimized_response - total_current_response) / total_current_response * 100, 1) if total_current_response > 0 else 0,
},
}
# ─────────────────────────────────────────────────────────────────
# PROMO-SPECIFIC MILP OPTIMIZATION
# ─────────────────────────────────────────────────────────────────
def run_promo_optimization(scope, constraints):
"""
MILP-based promo calendar optimization.
Returns optimized promo calendar with events.
"""
retailer = scope.get("retailer", "Shoppers Drug Mart")
category = scope.get("category", "Foods")
brand = scope.get("brand", "Brand 1")
start_date = pd.Timestamp(_to_date(scope["timePeriod"]["start"]))
end_date = pd.Timestamp(_to_date(scope["timePeriod"]["end"]))
kpi = constraints.get("businessKPI", "Profit")
objective = constraints.get("businessObjective", "Maximize")
tl = constraints.get("timeline", {})
max_weeks_promo = int(tl.get("maxWeeksOnPromotion", 15))
pr = constraints.get("product", {})
max_ppgs_on_promo = int(pr.get("maxProductsOnPromotion", 20))
pe = constraints.get("period", {})
min_dur = int(pe.get("minPromotionDuration", 1))
max_dur = int(pe.get("maxPromotionDuration", 15))
op = constraints.get("operational", {})
max_discount = float(op.get("maxDiscountDepth", 0.0))
baseline_by_ppg = sim_data_loader.get_all_ppgs_baseline(retailer, start_date, end_date)
all_ppg_ids = sorted(
p for p in sim_data_loader.get_all_ppg_ids(category, brand) if p in baseline_by_ppg
)
if not all_ppg_ids:
return {"error": f"No PPGs found for {category}/{brand} at {retailer}"}
all_weeks = _weeks_between(start_date.date(), end_date.date())
W = len(all_weeks)
P = len(all_ppg_ids)
M = len(MECHANICS_CATALOGUE)
# Pre-compute baseline values
ppg_week_base = {}
ppg_uplift = {}
for ppg_id in all_ppg_ids:
ppg_uplift[ppg_id] = sim_data_loader.get_uplift_row(ppg_id, retailer)
df = baseline_by_ppg[ppg_id]
for w_idx, week_date in enumerate(all_weeks):
ts = pd.Timestamp(week_date)
row = df[df["weekStartDate"] == ts]
if row.empty:
row = df.iloc[min(w_idx, len(df) - 1)]
else:
row = row.iloc[0]
ppg_week_base[(ppg_id, w_idx)] = {
"baselineUnits": float(row["baselineUnits"]),
"baselineNTS": float(row.get("baselineNTS", row["baselineGTS"])),
"regularPrice": float(row["regularPrice"]),
"unitCOGS": float(row["unitCOGS"]),
}
# Use heuristic optimization (greedy)
scores = []
for p, ppg_id in enumerate(all_ppg_ids):
uplift_row = ppg_uplift.get(ppg_id)
for w_idx in range(W):
base = ppg_week_base.get((ppg_id, w_idx), {})
base_units = base.get("baselineUnits", 0)
base_nts = base.get("baselineNTS", 0)
reg_price = base.get("regularPrice", 1)
unit_cogs = base.get("unitCOGS", 0)
base_gp = base_nts - base_units * unit_cogs
for m_idx, (_, offer_spec, uplift_col) in enumerate(MECHANICS_CATALOGUE):
disc = OFFER_DISCOUNT_MAP.get(offer_spec, 0)
if max_discount > 0 and disc > max_discount:
continue
promo_mult = float(uplift_row[uplift_col]) if (
uplift_row is not None and uplift_col in uplift_row.index) else 1.0
feat_mult = float(uplift_row.get("frontPage", 1.0)) if uplift_row is not None else 1.0
disp_mult = float(uplift_row.get("eventDisplay", 1.0)) if uplift_row is not None else 1.0
synergy = 1.0 + float(uplift_row.get("featureDisplaySynergy", 0.0)) if uplift_row is not None else 1.0
pantry_rate = float(uplift_row.get("pantryLoadingRate", 0.0)) if uplift_row is not None else 0.0
gross_lift = promo_mult * feat_mult * disp_mult * synergy
net_units = base_units * gross_lift * (1 - pantry_rate)
sim_nts = net_units * reg_price * (1 - disc)
sim_gp = sim_nts - net_units * unit_cogs
i_gp = sim_gp - base_gp
score = i_gp if kpi == "Profit" else (
(sim_nts - base_nts) if kpi == "Net Revenue" else (net_units - base_units)
)
scores.append((score, ppg_id, w_idx, m_idx))
scores.sort(key=lambda x: x[0], reverse=(objective == "Maximize"))
# Greedy assignment
ppg_weeks_used = {p: 0 for p in all_ppg_ids}
assigned = {}
week_ppg_count = {}
for score, ppg_id, w_idx, m_idx in scores:
if score <= 0:
break
if ppg_weeks_used[ppg_id] >= max_weeks_promo:
continue
if week_ppg_count.get(w_idx, 0) >= max_ppgs_on_promo:
continue
if (ppg_id, w_idx) in assigned:
continue
run_len = min(min_dur, W - w_idx)
for ww in range(w_idx, min(w_idx + run_len, W)):
if ppg_weeks_used[ppg_id] < max_weeks_promo:
assigned[(ppg_id, ww)] = m_idx
ppg_weeks_used[ppg_id] += 1
week_ppg_count[ww] = week_ppg_count.get(ww, 0) + 1
# Build optimized events
from itertools import groupby
opt_events = []
for ppg_id in all_ppg_ids:
ppg_weeks = sorted([ww for (pid, ww), mid in assigned.items() if pid == ppg_id])
if not ppg_weeks:
continue
for _, group in groupby(enumerate(ppg_weeks), key=lambda x: x[1] - x[0]):
run = [ww for _, ww in group]
m_idx = assigned[(ppg_id, run[0])]
mechanic_name, offer_spec, _ = MECHANICS_CATALOGUE[m_idx]
opt_events.append({
"productFamily": ppg_id,
"promoMechanic": mechanic_name,
"offerSpec": offer_spec,
"feature": "FEATURE",
"display": "disp_w_feat",
"startDate": all_weeks[run[0]].isoformat(),
"endDate": all_weeks[run[-1]].isoformat(),
})
# Run simulation on optimized events
baseline_result = run_promo_simulation(scope, [])
opt_result = run_promo_simulation(scope, opt_events) if opt_events else baseline_result
return {
"baseline": baseline_result,
"optimized": opt_result,
"optimizedEvents": opt_events,
}