{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "scope",
   "metadata": {},
   "source": [
    "# Inside the MMM Dataset: design audit\n",
    "Read-only reproduction of the descriptive results in Quan Insights' dataset-design article. Uses Python's standard library; no package installation is needed.\n",
    "\n",
    "The default source is the publicly released MMM Dataset v1.0. SHA-256 hashes verify that the files match the audited release. This notebook does not fit an MMM, test parameter recovery, or validate budget recommendations. Truth columns are used only to evaluate generating relationships."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "load",
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import hashlib\n",
    "import io\n",
    "import json\n",
    "import math\n",
    "import statistics\n",
    "from datetime import date\n",
    "from pathlib import Path\n",
    "from urllib.request import Request, urlopen\n",
    "\n",
    "BASE_URL = 'https://quaninsights.com/data/mmm'\n",
    "EXPECTED_SHA256 = {\n",
    "    'mmm-dataset.csv': 'e2db7ab17a4256ca7d70c7c292e947ae6aa3b90a1eb7601c0679bcb0ac189255',\n",
    "    'mmm-dataset-params.json': '53928fb64b6c851cb6bd62e915e0509ea997a1cd078ec5845b7cf8270be189f6',\n",
    "}\n",
    "# Set LOCAL_DATA_DIR to a checkout's public/data/mmm directory for an offline audit.\n",
    "LOCAL_DATA_DIR = None\n",
    "\n",
    "def read_source(name):\n",
    "    if LOCAL_DATA_DIR is not None:\n",
    "        payload = (Path(LOCAL_DATA_DIR) / name).read_bytes()\n",
    "    else:\n",
    "        request = Request(f'{BASE_URL}/{name}', headers={'User-Agent': 'QuanInsightsDatasetAudit/1.0', 'Accept': 'text/csv, application/json'})\n",
    "        with urlopen(request, timeout=30) as response:\n",
    "            payload = response.read()\n",
    "    if hashlib.sha256(payload).hexdigest() != EXPECTED_SHA256[name]:\n",
    "        raise ValueError(f'{name} differs from the audited v1.0 release. Do not reuse the article results without a new audit.')\n",
    "    return payload.decode('utf-8')\n",
    "\n",
    "reader = csv.DictReader(io.StringIO(read_source('mmm-dataset.csv')))\n",
    "headers = reader.fieldnames\n",
    "raw_rows = list(reader)\n",
    "params = json.loads(read_source('mmm-dataset-params.json'))\n",
    "assert params['version'] == '1.0.0', 'This audit describes v1.0.'\n",
    "rows = [{key: value if key == 'date' else float(value) for key, value in row.items()} for row in raw_rows]\n",
    "\n",
    "def column(name):\n",
    "    return [row[name] for row in rows]\n",
    "\n",
    "def pearson(left, right):\n",
    "    left_mean, right_mean = statistics.mean(left), statistics.mean(right)\n",
    "    numerator = sum((a - left_mean) * (b - right_mean) for a, b in zip(left, right))\n",
    "    denominator = math.sqrt(sum((a - left_mean)**2 for a in left) * sum((b - right_mean)**2 for b in right))\n",
    "    if denominator == 0:\n",
    "        raise ValueError('Correlation is undefined for a constant column.')\n",
    "    return numerator / denominator\n",
    "\n",
    "print('Source:', BASE_URL if LOCAL_DATA_DIR is None else LOCAL_DATA_DIR)\n",
    "print('Dataset version:', params['version'], '| seed:', params['seed'])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "quality-note",
   "metadata": {},
   "source": [
    "## Calendar, completeness, and information sets\n",
    "The practitioner information set is `observedColumns`. Never add `truthColumns` or the true channel parameters to an estimated model just because they are available in this teaching release."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "quality",
   "metadata": {},
   "outputs": [],
   "source": [
    "assert len(rows) == params['weekCount'] == 156\n",
    "assert len(headers) == len(set(headers)) == 27\n",
    "assert all(None not in row and len(row) == len(headers) for row in raw_rows)\n",
    "assert all(value is not None and value != '' for row in raw_rows for value in row.values())\n",
    "assert all(math.isfinite(value) for row in rows for key, value in row.items() if key != 'date')\n",
    "dates = [date.fromisoformat(row['date']) for row in rows]\n",
    "assert len(dates) == len(set(dates))\n",
    "assert all((later - earlier).days == 7 for earlier, later in zip(dates, dates[1:]))\n",
    "assert column('week') == list(range(1, len(rows) + 1))\n",
    "observed = set(params['observedColumns'])\n",
    "truth = set(params['truthColumns'])\n",
    "assert observed.isdisjoint(truth)\n",
    "assert observed | truth == set(headers)\n",
    "print(f'{len(rows)} rows, {len(headers)} columns; {len(observed)} observed and {len(truth)} truth columns')\n",
    "print(f'{dates[0]} to {dates[-1]}: complete weekly calendar, no missing or nonfinite values')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "mechanism-note",
   "metadata": {},
   "source": [
    "## Generating relationships\n",
    "The generator calculates with unrounded values and stores two-decimal media and truth columns. Recomputing from the CSV therefore needs small rounding tolerances. These checks audit consistency, not statistical identification."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "mechanism",
   "metadata": {},
   "outputs": [],
   "source": [
    "max_adstock_error = max_contribution_error = 0.0\n",
    "for channel, spec in params['channels'].items():\n",
    "    previous = 0.0\n",
    "    for row in rows:\n",
    "        spend = row[f'{channel}_spend']\n",
    "        stock = row[f'{channel}_adstock']\n",
    "        actual = row[f'{channel}_contribution']\n",
    "        assert spend >= 0 and stock >= 0 and actual >= 0\n",
    "        max_adstock_error = max(max_adstock_error, abs(stock - spend - spec['lambda'] * previous))\n",
    "        power = stock ** spec['slope']\n",
    "        expected = spec['beta'] * power / (spec['halfSaturation'] ** spec['slope'] + power)\n",
    "        max_contribution_error = max(max_contribution_error, abs(actual - expected))\n",
    "        previous = stock\n",
    "max_media_error = max(abs(sum(row[f'{channel}_contribution'] for channel in params['channels']) - row['total_media_contribution']) for row in rows)\n",
    "max_total_error = max(abs(row['base_demand'] + row['total_media_contribution'] - row['expected_subscriptions']) for row in rows)\n",
    "assert max_adstock_error <= 0.015\n",
    "assert max_contribution_error <= 0.01\n",
    "assert max_media_error <= 0.031\n",
    "assert max_total_error <= 0.011\n",
    "print(f'Max adstock residual: {max_adstock_error:.4f}')\n",
    "print(f'Max contribution residual: {max_contribution_error:.4f}')\n",
    "print(f'Max channel-sum residual: {max_media_error:.4f}')\n",
    "print(f'Max expected-outcome residual: {max_total_error:.4f}')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "coverage",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Channel | Spend range ($K) | Zero weeks | Median adstock/K | Weeks above K')\n",
    "for channel, spec in params['channels'].items():\n",
    "    spend = column(f'{channel}_spend')\n",
    "    stock = column(f'{channel}_adstock')\n",
    "    half_saturation = spec['halfSaturation']\n",
    "    zeros = sum(value == 0 for value in spend)\n",
    "    above = sum(value > half_saturation for value in stock)\n",
    "    ratio = statistics.median(stock) / half_saturation\n",
    "    print(f\"{spec['label']} | {min(spend):.2f}-{max(spend):.2f} | {zeros} | {ratio:.2f} | {above}/{len(rows)}\")\n",
    "social_ratio = [value / params['channels']['paid_social']['halfSaturation'] for value in column('paid_social_adstock')]\n",
    "print(f'Social adstock range: {min(social_ratio):.2f}K-{max(social_ratio):.2f}K')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "correlations",
   "metadata": {},
   "outputs": [],
   "source": [
    "pairs = [\n",
    "    ('Social/CTV spend', 'paid_social_spend', 'ctv_video_spend'),\n",
    "    ('Social/CTV true adstock', 'paid_social_adstock', 'ctv_video_adstock'),\n",
    "    ('CTV/Podcast true adstock', 'ctv_video_adstock', 'podcast_audio_adstock'),\n",
    "    ('Search spend/promotion', 'paid_search_spend', 'promo_flag'),\n",
    "]\n",
    "for label, left, right in pairs:\n",
    "    print(f'{label}: {pearson(column(left), column(right)):.3f}')\n",
    "noise = [row['observed_subscriptions'] - row['expected_subscriptions'] for row in rows]\n",
    "print(f'Outcome residual sample SD: {statistics.stdev(noise):.2f} subscriptions')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "interpretation",
   "metadata": {},
   "source": [
    "## Interpretation\n",
    "The released dataset is internally consistent with its known generating rules. Social and CTV schedules are weakly correlated in this sample; a high-correlation study must introduce that condition explicitly. Social's observed adstock covers a limited part of the true Hill curve.\n",
    "\n",
    "These are descriptive results for one seed and one parameter setting. Parameter recovery, uncertainty coverage, and allocation regret require fitted models and repeated simulations under a defined decision protocol. Neither zero-spend weeks nor low pairwise correlation automatically establish causal identification.\n",
    "\n",
    "To check generator reproducibility separately, run `node scripts/generate-mmm-dataset.mjs` in a repository checkout and compare the generated CSV with the hash-verified release. That command rewrites the CSV and parameter JSON in the checkout. This notebook only reads data."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
