{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2ef9e317",
   "metadata": {},
   "source": [
    "# Anthropometric & Sizing Physics Simulation (N = 10,000,000)\n",
    "\n",
    "**Published by Rendered Fits** · [Interactive Study Hub](https://www.renderedfits.com/anthropometric-fit-simulation-2026/) · Licence: CC BY 4.0\n",
    "\n",
    "This notebook reproduces the full **10,000,000-shopper GPU-accelerated Monte Carlo sizing physics simulation** across **59 verified UK & US women's fashion retailer size charts** in under 60 seconds on a Google Colab T4/L4/A100 GPU (with automatic PyTorch `cuda`/`mps` and vectorised NumPy fallback).\n",
    "\n",
    "**Headline benchmarks (from the published 10M run):**\n",
    "- Mean split-size conflict across 58 three-measurement retailers: **91.31%** of in-range shoppers (`36.13%` 1-size split, `55.18%` 2+-size split)\n",
    "- Mean cross-brand `>4 cm` fit-discrepancy risk across `3,422` directed brand pairs: **52.6%**\n",
    "- Fit-error variance drops **44.69%** (and MAE drops **27.41%**) from Height+Weight alone (`3.338 cm`) to 3 body measurements + garment ease/stretch (`2.423 cm`)\n",
    "\n",
    "> **Transparent disclosure:** Shopper body profiles are synthetically sampled from public-domain anthropometric parameters (US CDC NHANES 2015–2018, US Army ANSUR II 2012, UK SizeUK/ONS). Retailer size charts are real verified published charts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cde761e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Detect GPU (CUDA / Apple MPS) or CPU fallback & load libraries\n",
    "import json, math, time, urllib.request\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "try:\n",
    "    import torch\n",
    "    if torch.cuda.is_available():\n",
    "        DEVICE = torch.device('cuda')\n",
    "        print('GPU detected:', torch.cuda.get_device_name(0))\n",
    "    elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():\n",
    "        DEVICE = torch.device('mps')\n",
    "        print('Apple Silicon Metal GPU (MPS) detected')\n",
    "    else:\n",
    "        DEVICE = torch.device('cpu')\n",
    "        print('Running PyTorch on CPU')\n",
    "except ImportError:\n",
    "    torch = None\n",
    "    DEVICE = None\n",
    "    print('PyTorch not installed; using vectorised float32 NumPy fallback')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c2cc1fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. Download the published open datasets (JSON / Parquet / CSV) from renderedfits.com\n",
    "BASE = 'https://www.renderedfits.com/open-data/datasets/anthropometric-fit-simulation-2026'\n",
    "\n",
    "def fetch_json(name):\n",
    "    with urllib.request.urlopen(f'{BASE}/{name}') as resp:\n",
    "        return json.loads(resp.read().decode('utf-8'))\n",
    "\n",
    "summary = fetch_json('summary.json')\n",
    "atlas_df = pd.read_parquet(f'{BASE}/split-size-conflict-atlas.parquet')\n",
    "matrix_df = pd.read_parquet(f'{BASE}/cross-brand-fit-failure-matrix.parquet')\n",
    "entropy_df = pd.read_parquet(f'{BASE}/dimensionality-entropy-curve.parquet')\n",
    "\n",
    "print(f\"Loaded {len(atlas_df)} brands, {len(matrix_df):,} directed brand pairs, {len(entropy_df)} entropy stages.\")\n",
    "display(atlas_df[['conflict_rank', 'brand_name', 'region', 'any_split_pct', 'split_1_size_pct', 'split_2plus_sizes_pct', 'dominant_conflict_pair']].head(15))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49b13719",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. Live GPU Monte Carlo Reproduction (N = 10,000,000 adult female profiles)\n",
    "N_SIM = 10_000_000\n",
    "CHUNK = 1_000_000\n",
    "SEED = 20261204\n",
    "\n",
    "MEANS = np.array([162.5, 72.1, 96.4, 80.2, 103.8], dtype=np.float64)\n",
    "SDS   = np.array([6.7, 15.8, 10.6, 11.4, 10.2], dtype=np.float64)\n",
    "CORR  = np.array([\n",
    "    [1.00, 0.34, 0.14, 0.11, 0.22],\n",
    "    [0.34, 1.00, 0.84, 0.85, 0.88],\n",
    "    [0.14, 0.84, 1.00, 0.82, 0.76],\n",
    "    [0.11, 0.85, 0.82, 1.00, 0.79],\n",
    "    [0.22, 0.88, 0.76, 0.79, 1.00],\n",
    "], dtype=np.float64)\n",
    "\n",
    "sigma2 = np.log1p((SDS / MEANS) ** 2)\n",
    "sigma = np.sqrt(sigma2)\n",
    "mu = np.log(MEANS) - 0.5 * sigma2\n",
    "cov = np.outer(sigma, sigma) * CORR\n",
    "chol = np.linalg.cholesky(cov)\n",
    "\n",
    "# Live GPU verification against Zara UK 4-16 published chart (cm)\n",
    "zara_b = np.array([80, 82, 86, 90, 96, 102, 108], dtype=np.float32)\n",
    "zara_w = np.array([58, 62, 66, 70, 76, 82, 88], dtype=np.float32)\n",
    "zara_h = np.array([86, 90, 94, 98, 104, 110, 116], dtype=np.float32)\n",
    "\n",
    "t0 = time.perf_counter()\n",
    "in_range_n = split1_n = split2_n = 0\n",
    "\n",
    "if torch is not None and DEVICE is not None:\n",
    "    gen = torch.Generator(device=DEVICE).manual_seed(SEED)\n",
    "    mu_t = torch.tensor(mu, dtype=torch.float32, device=DEVICE)\n",
    "    ch_t = torch.tensor(chol, dtype=torch.float32, device=DEVICE)\n",
    "    be = torch.tensor(0.5*(zara_b[:-1]+zara_b[1:]), device=DEVICE)\n",
    "    we = torch.tensor(0.5*(zara_w[:-1]+zara_w[1:]), device=DEVICE)\n",
    "    he = torch.tensor(0.5*(zara_h[:-1]+zara_h[1:]), device=DEVICE)\n",
    "    for _ in range(N_SIM // CHUNK):\n",
    "        x = torch.exp(mu_t + torch.randn((CHUNK, 5), device=DEVICE, generator=gen) @ ch_t.T)\n",
    "        b, w, h = x[:, 2].contiguous(), x[:, 3].contiguous(), x[:, 4].contiguous()\n",
    "        ok = (b >= 79.0) & (b <= 111.0) & (w >= 56.0) & (w <= 91.0) & (h >= 84.0) & (h <= 119.0)\n",
    "        ib, iw, ih = torch.bucketize(b[ok], be), torch.bucketize(w[ok], we), torch.bucketize(h[ok], he)\n",
    "        sp = torch.maximum(torch.maximum(ib, iw), ih) - torch.minimum(torch.minimum(ib, iw), ih)\n",
    "        in_range_n += int(ok.sum().item())\n",
    "        split1_n += int((sp == 1).sum().item())\n",
    "        split2_n += int((sp >= 2).sum().item())\n",
    "else:\n",
    "    rng = np.random.default_rng(SEED)\n",
    "    be, we, he = 0.5*(zara_b[:-1]+zara_b[1:]), 0.5*(zara_w[:-1]+zara_w[1:]), 0.5*(zara_h[:-1]+zara_h[1:])\n",
    "    for _ in range(N_SIM // CHUNK):\n",
    "        x = np.exp(mu.astype(np.float32) + rng.standard_normal((CHUNK, 5), dtype=np.float32) @ chol.T.astype(np.float32))\n",
    "        b, w, h = x[:, 2], x[:, 3], x[:, 4]\n",
    "        ok = (b >= 79.0) & (b <= 111.0) & (w >= 56.0) & (w <= 91.0) & (h >= 84.0) & (h <= 119.0)\n",
    "        ib, iw, ih = np.searchsorted(be, b[ok]), np.searchsorted(we, w[ok]), np.searchsorted(he, h[ok])\n",
    "        sp = np.maximum(np.maximum(ib, iw), ih) - np.minimum(np.minimum(ib, iw), ih)\n",
    "        in_range_n += int(np.count_nonzero(ok))\n",
    "        split1_n += int(np.count_nonzero(sp == 1))\n",
    "        split2_n += int(np.count_nonzero(sp >= 2))\n",
    "\n",
    "dt = time.perf_counter() - t0\n",
    "print(f'Simulated N={N_SIM:,} profiles in {dt:.2f}s!')\n",
    "print(f'Zara in-range shoppers: {in_range_n:,} ({100*in_range_n/N_SIM:.2f}%)')\n",
    "print(f'Zara split-size conflict: {100*(split1_n+split2_n)/in_range_n:.2f}% (1-size: {100*split1_n/in_range_n:.2f}%, 2+-size: {100*split2_n/in_range_n:.2f}%)')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a95c0fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4. Inspect the Measurement-Dimensionality Entropy Curve & Highest-Risk Brand Pairs\n",
    "display(entropy_df[['stage_label', 'mean_abs_fit_error_cm', 'fit_error_variance_cm2', 'variance_reduction_vs_height_weight_pct', 'size_error_shannon_entropy_bits', 'prob_error_gt_4cm_pct']])\n",
    "\n",
    "print('\\nTop 10 Highest Cross-Brand Fit-Failure Pairs (same nominal size, >4 cm discrepancy):')\n",
    "display(matrix_df.sort_values(['prob_discrepancy_gt_4cm_pct', 'prob_discrepancy_gt_6cm_pct'], ascending=False)\n",
    "        [['from_brand_name', 'to_brand_name', 'prob_discrepancy_gt_4cm_pct', 'prob_discrepancy_gt_6cm_pct', 'mean_max_discrepancy_cm', 'dominant_failure_dimension']].head(10))\n"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "name": "anthropometric-sizing-simulation-10m.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
