{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d731b9d9",
   "metadata": {},
   "source": [
    "# Borrowing of strength in Bayesian hierarchical model\n",
    "We consider the problem of estimating the average number of patients admitted to\n",
    "ER per day from various hospitals across a city. A Bayesian hierarchical model\n",
    "(BHM) allows us to partially pool information across hospitals, reducing\n",
    "variance in small-sample groups and leveraging strength across hospitals to\n",
    "estimate the population-level parameters. Here, we investigate a Poisson-\n",
    "lognormal model.\n",
    "\n",
    "(a) Generate a dataset where the logarithm of the expected number of admissions\n",
    "    per day for hospital $j$, $ln \\lambda_j$, comes from a Normal distribution:\n",
    "\n",
    "$$ ln \\lambda_j \\sim \\mathcal{N}(\\mu_0,\\,\\sigma_0^{2}), \\text{ for } j = 1, ..., J $$\n",
    "\n",
    "The admission counts data for each hospital for day $i$ follow a Poisson\n",
    "distribution:\n",
    "\n",
    "$$ y_{ij} \\mid \\lambda_j \\sim \\text{Poisson}(\\lambda_j), \\text{ for } i = 1, ..., n_j $$\n",
    "\n",
    "where each hospital $j$ has a different reporting frequency, which leads to\n",
    "different $n_j$ for each. To model this, you may draw $n_j$ randomly with equal\n",
    "probability from the set $\\{52, 24, 12\\}$, representing respectively weekly,\n",
    "twice a month and monthly reporting. Do this once, and keep $n_j$ fixed,\n",
    "treating it as known, throughout the exercise.\n",
    "\n",
    "The DAG for this model is shown in the figure.\n",
    "\n",
    "![Figure 1: DAG for hospital admission BHM](./figure_1.pdf)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5655aaf",
   "metadata": {},
   "source": [
    "Since $\\mu_0$ is the typical log-rate\n",
    "across hospitals, we may choose for its prior\n",
    "$$Pr(\\mu_0) = \\mathcal{N}(\\log m, s^2)$$\n",
    "\n",
    "where $m$ is a plausible choice for the median number of admissions/day, and s\n",
    "controls its spread. Since $\\sigma_0$ controls the variability across hospitals,\n",
    "a prior choice that tends to reinforce shrinkage is $Pr(\\sigma_0) = \\exp(\\tau)$.\n",
    "\n",
    "Fix $m$, $s^2$, $\\tau$ to sensible values, and use an MCMC algorithm of your\n",
    "choice to sample from the model and produce posterior distribution on\n",
    "$\\{\\lambda_j\\}^J_{j=1}, \\mu _0, \\sigma _0$ (a sensible choice might be $J = 10$\n",
    "hospitals).\n",
    "\n",
    "____\n",
    "\n",
    "(b) Determine the marginal posterior distribution for the admission rate for\n",
    "each hospital, and compare it with the posterior estimate in a model with no\n",
    "pooling (i.e., where each hospital’s rate is inferred exclusively from its\n",
    "observed counts, i.e. $\\ln \\lambda_j \\sim \\mathcal{N} (\\mu_0, \\sigma^2_0)$ and\n",
    "the same priors as above, and the posterior for hospital j comes exclusively\n",
    "from its own data). Check that the posterior means for hospitals with a smaller\n",
    "number of records (i.e., $n_j = 12$) exhibit stronger shrinkage towards the\n",
    "global mean, thus demonstrating borrowing of strength, and typically have 68%\n",
    "HPD credible intervals that are shorter than in the pooling model. You may use a\n",
    "violin plot to make this comparison.\n",
    "\n",
    "___\n",
    "\n",
    "(c) Consider the prior predictive distribution for possible data within the BHM:\n",
    "\n",
    "$$ Pr( y_{ij} \\mid priors) = \\int Pr ( y_{ij} \\mid \\lambda_j) Pr(\\lambda_j \\mid \\mu_0, \\sigma_0) Pr (\\mu_0,\\sigma_0) d \\mu_0 d \\sigma_0$$\n",
    "\n",
    "and simulate from it predictions for the possible counts $y_{ij}$ from the model\n",
    "(before you see any data). Evaluate the degree of shrinkage by using as metric\n",
    "the average shrinkage in the standard deviation of the posterior with respect to\n",
    "the no-pooling scenario, i.e.\n",
    "\n",
    "$$ S = \\frac {1} {J} \\sum_{j=1}^{J}{1 - \\frac{\\text{std}_\\text{BHM}(\\ln \\lambda_j \\mid \\bold y)}{\\text{std}_\\text{no pool}(\\ln \\lambda_j \\mid \\bold y)}}$$\n",
    "\n",
    "where a smaller S corresponds to higher degree of shrinkage.\n",
    "\n",
    "Determine which hyperparameter among $(m, s, \\tau)$ has the most effect on the\n",
    "degree of shrinkage, and tune each to avoid predictions that are too diffuse\n",
    "(i.e., the predictive spread is unreasonably wide) or too narrow (i.e., the\n",
    "predictive spread is over-constraining)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49307215",
   "metadata": {},
   "outputs": [],
   "source": [
    "import corner\n",
    "import emcee\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.special import gammaln\n",
    "from scipy.stats import pearsonr\n",
    "\n",
    "np.random.seed(42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "af15e048",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "We have 10 hospitals reporting admission data.\n",
      "- Hospital number  1 reports admission data 12 times a year.\n",
      "- Hospital number  2 reports admission data 54 times a year.\n",
      "- Hospital number  3 reports admission data 12 times a year.\n",
      "- Hospital number  4 reports admission data 12 times a year.\n",
      "- Hospital number  5 reports admission data 54 times a year.\n",
      "- Hospital number  6 reports admission data 54 times a year.\n",
      "- Hospital number  7 reports admission data 12 times a year.\n",
      "- Hospital number  8 reports admission data 24 times a year.\n",
      "- Hospital number  9 reports admission data 12 times a year.\n",
      "- Hospital number 10 reports admission data 12 times a year.\n"
     ]
    }
   ],
   "source": [
    "J = 10\n",
    "reporting_frequency = np.random.choice(\n",
    "    [54, 24, 12],\n",
    "    J\n",
    ")\n",
    "\n",
    "print(f\"We have {J} hospitals reporting admission data.\")\n",
    "for j in range(J):\n",
    "    print(\n",
    "        f\"- Hospital number {j + 1:2} reports admission data \"\n",
    "        f\"{reporting_frequency[j]} times a year.\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4a09b1d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "true_lambdas = []\n",
    "\n",
    "def get_expected_admission_counts(mu: float, sigma: float, size: int):\n",
    "    \"\"\"Get expected number of admissions to a hospital at 'size' time points.\n",
    "    \n",
    "    The log of the admission rate comes from a normal distribution with mean\n",
    "        'mu' and standard deviation 'sigma'.\n",
    "    The expected number of admissions comes from a Poisson distribution with\n",
    "        parameter 'admission_rate'.\n",
    "    From the same Poisson distribution, 'size' time points will be sampled.\n",
    "    \"\"\"\n",
    "    log_admission_rate = np.random.normal(\n",
    "        mu, sigma\n",
    "    )\n",
    "    admission_rate = np.exp(log_admission_rate)\n",
    "    true_lambdas.append(admission_rate)\n",
    "    admission_counts = np.random.poisson(\n",
    "        admission_rate, size=size\n",
    "    )\n",
    "    return admission_counts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2f6b2f3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_admission_count_matrix(mu: float, sigma: float) -> pd.DataFrame:\n",
    "    data = {}\n",
    "    total_array_length = max(reporting_frequency)\n",
    "    for j in range(J):  # For each hospital\n",
    "        data_array_length = reporting_frequency[j]\n",
    "        admission_records = get_expected_admission_counts(\n",
    "            mu, sigma, size=data_array_length\n",
    "        )\n",
    "        padding = np.full(total_array_length - data_array_length, 0, dtype=int)\n",
    "        admission_records = np.concatenate([\n",
    "            admission_records,\n",
    "            padding\n",
    "        ])\n",
    "        data[f\"Hospital {j+1}\"] = admission_records\n",
    "    data = pd.DataFrame(data)\n",
    "    data.index.name = \"Time point\"\n",
    "    return data.transpose()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6015dc49",
   "metadata": {},
   "source": [
    "- Prior for $\\mu_0$: we choose $m$ (typical log-rate across hospitals) and $s$\n",
    "(a measure of the spread of $m$); $Pr(\\mu_0) = \\mathcal{N}(\\log m, s^2)$.\n",
    "- Prior for $\\sigma_0$: $Pr(\\sigma_0) = \\text{Exponential}(\\tau)$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "216cdb28",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = 85\n",
    "s = 0.4\n",
    "tau = 0.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4b5ee692",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time point    0    1    2    3    4    5    6    7    8    9   ...   44   45  \\\n",
      "Hospital 1   149  147  161  152  144  155  171  161  146  173  ...    0    0   \n",
      "Hospital 2   180  166  160  178  182  147  153  151  154  161  ...  150  152   \n",
      "Hospital 3   174  147  163  149  146  156  144  142  177  166  ...    0    0   \n",
      "Hospital 4   154  178  170  138  178  165  145  167  148  149  ...    0    0   \n",
      "Hospital 5   163  155  156  165  160  160  169  155  183  175  ...  143  168   \n",
      "Hospital 6   163  162  165  161  156  180  136  167  153  151  ...  142  165   \n",
      "Hospital 7   167  165  179  178  164  147  154  161  173  146  ...    0    0   \n",
      "Hospital 8   145  155  174  159  151  176  162  150  164  166  ...    0    0   \n",
      "Hospital 9   183  150  153  150  143  145  165  154  159  146  ...    0    0   \n",
      "Hospital 10  154  167  171  138  181  151  169  148  159  154  ...    0    0   \n",
      "\n",
      "Time point    46   47   48   49   50   51   52   53  \n",
      "Hospital 1     0    0    0    0    0    0    0    0  \n",
      "Hospital 2   160  151  149  150  170  168  165  161  \n",
      "Hospital 3     0    0    0    0    0    0    0    0  \n",
      "Hospital 4     0    0    0    0    0    0    0    0  \n",
      "Hospital 5   141  159  158  164  130  165  176  146  \n",
      "Hospital 6   163  155  176  194  199  178  162  161  \n",
      "Hospital 7     0    0    0    0    0    0    0    0  \n",
      "Hospital 8     0    0    0    0    0    0    0    0  \n",
      "Hospital 9     0    0    0    0    0    0    0    0  \n",
      "Hospital 10    0    0    0    0    0    0    0    0  \n",
      "\n",
      "[10 rows x 54 columns]\n"
     ]
    }
   ],
   "source": [
    "true_mu_0 = np.random.normal(np.log(m), s)\n",
    "true_sigma_0 = np.random.exponential(tau)\n",
    "\n",
    "df = get_admission_count_matrix(mu=true_mu_0, sigma=true_sigma_0)\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c8afdbc",
   "metadata": {},
   "source": [
    "We can use AIES (ensemble samplers with affine invariance), introduced by\n",
    "Goodman and Weare in 2010 and implemented by the `emcee` python package, to\n",
    "sample from the joint posterior without analytically deriving it.\n",
    "\n",
    "We have to write a function that takes in all hyper-parameters (both fixed and\n",
    "unknown) and returns the posterior value for those parameters; we will then\n",
    "construct an `emcee.EnsembleSampler` (giving the number of unknown parameters\n",
    "and the known ones) and we will finally run MCMC for a certain number of steps.\n",
    "The sampler will return tuples of sampled parameters.\n",
    "\n",
    "For analytical convenience, we will use $\\ln(Posterior)$, $\\ln(\\text{Prior})$\n",
    "and $\\ln(\\mathcal{L})$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "35c25880",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "j=6\n",
    "type(df.iloc[j,:reporting_frequency[j]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10a1de3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def log_posterior(parameters, m: float, s: float, tau: float, J: int):\n",
    "    # lambda_j is an array of length J with the admission rate for each hospital\n",
    "    mu_0, sigma_0, *lambdas = parameters\n",
    "    # Check parameters that have to be strictly positive\n",
    "    if sigma_0 <= 0:  # Standard deviation of a Normal distribution\n",
    "        return -np.inf\n",
    "    if any(l <= 0 for l in lambdas):  # Frequency of a Poisson distribution\n",
    "        return -np.inf\n",
    "    log_prior = 0.0\n",
    "    # Prior for 'mu_0' (normally distributed, parameters 'm' and 's')\n",
    "    log_prior += (\n",
    "        -0.5 * np.log(2 * np.pi * s**2)\n",
    "        -0.5 * ((mu_0 - np.log(m))**2) / s**2\n",
    "    )\n",
    "    # Prior for 'sigma_0' (exponentially distributed, parameter 'tau')\n",
    "    log_prior += (\n",
    "         np.log(tau) - tau * sigma_0\n",
    "    )\n",
    "    log_likelihood = 0.0\n",
    "    # Prior for 'lambdas' (each log-normally distributed, parameters 'mu_0', 'sigma_0')\n",
    "    # and likelihood of 'observed_admissions' (Poisson distributed, parameter 'lambdas[j]')\n",
    "    # We only iterate once over range(J) for the sake of efficiency\n",
    "    for j in range(J):\n",
    "        log_prior += (\n",
    "            -np.log(lambdas[j] * sigma_0 * np.sqrt(2 * np.pi))\n",
    "            - ((np.log(lambdas[j]) - mu_0)**2) / (2 * sigma_0**2)\n",
    "        )\n",
    "        # Get the observed admission counts for hospital j,\n",
    "        #   and cast it to a numpy array for efficiency\n",
    "        # This is equivalent to (but faster than) a for loop\n",
    "        #   for i in range(reporting_frequency[j]):\n",
    "        #       reporting_frequency = df.iloc[j, i]\n",
    "        #       log_likelihood += (...)\n",
    "        observed_admissions = df.iloc[j,:reporting_frequency[j]].to_numpy()\n",
    "        log_likelihood += np.sum(\n",
    "            observed_admissions * np.log(lambdas[j])\n",
    "            - lambdas[j]\n",
    "            - gammaln(observed_admissions+1)\n",
    "        )\n",
    "    return log_prior + log_likelihood"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "1e393c9f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5000/5000 [03:36<00:00, 23.12it/s]\n"
     ]
    }
   ],
   "source": [
    "# Data: observed_admissions (from previous synthetic data generation)\n",
    "# Assuming observed_admissions is a pandas df (J * max(reporting_frequency))\n",
    "\n",
    "# Number of dimensions and walkers\n",
    "ndim = 2 + J  # [mu_0, sigma_0, lambda_1, ..., lambda_J]\n",
    "num_walkers = 32\n",
    "\n",
    "# Initial guess for parameters\n",
    "initial_guess = [\n",
    "      true_mu_0,\n",
    "      true_sigma_0,\n",
    "      *true_lambdas\n",
    "]\n",
    "\n",
    "# Initialize walkers in a small ball around the initial guess\n",
    "pos = initial_guess + 1e-4 * np.random.randn(num_walkers, ndim)\n",
    "\n",
    "# Create the sampler\n",
    "sampler = emcee.EnsembleSampler(\n",
    "      num_walkers, ndim, log_posterior,\n",
    "      args=(m, s, tau, J)\n",
    ")\n",
    "\n",
    "# Run MCMC\n",
    "nsteps = 5000\n",
    "sampler.run_mcmc(pos, nsteps, progress=True)\n",
    "\n",
    "# Get one sample every 'thin' steps, discarding the burn-in (first 'discard' steps)\n",
    "samples = sampler.get_chain(discard=1000, thin=10, flat=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "bcedf091",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 2136908 characters]",
      "text/plain": [
       "<Figure size 2650x2650 with 144 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Labels and true values\n",
    "labels = [r'$\\mu_0$', r'$\\sigma_0$', *[rf'$\\lambda_{{{j + 1}}}$' for j in range(J)]]\n",
    "truths = [true_mu_0, true_sigma_0, *true_lambdas]\n",
    "\n",
    "# Create a corner plot\n",
    "fig = corner.corner(\n",
    "    samples,\n",
    "    labels=labels,\n",
    "    truths=truths,\n",
    "    quantiles=[0.16, 0.5, 0.84],\n",
    "    show_titles=True,\n",
    "    title_kwargs={\"fontsize\": 12}\n",
    ")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ce8571e",
   "metadata": {},
   "source": [
    "### (b) Here are the marginal posterior distributions of admission rates for every hospital:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "03ee076c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          Reporting frequency  16th percentile  84th percentile  \\\n",
      "Hospital                                                          \n",
      "1                          12       155.772971       160.241098   \n",
      "2                          54       157.656116       160.502618   \n",
      "3                          12       156.272260       160.602153   \n",
      "4                          12       158.177209       162.292523   \n",
      "5                          54       157.382752       160.187262   \n",
      "6                          54       160.169699       163.533840   \n",
      "7                          12       158.731447       162.830338   \n",
      "8                          24       159.015641       162.708823   \n",
      "9                          12       154.559953       159.806722   \n",
      "10                         12       157.219515       161.435273   \n",
      "\n",
      "          HPD width (68%)      mu_0   sigma_0  \n",
      "Hospital                                       \n",
      "1                4.468127  5.070992  0.016259  \n",
      "2                2.846502  5.070992  0.016259  \n",
      "3                4.329893  5.070992  0.016259  \n",
      "4                4.115313  5.070992  0.016259  \n",
      "5                2.804511  5.070992  0.016259  \n",
      "6                3.364141  5.070992  0.016259  \n",
      "7                4.098891  5.070992  0.016259  \n",
      "8                3.693182  5.070992  0.016259  \n",
      "9                5.246769  5.070992  0.016259  \n",
      "10               4.215758  5.070992  0.016259  \n"
     ]
    }
   ],
   "source": [
    "rows = []\n",
    "\n",
    "for j in range(J):\n",
    "    mu_0_j = samples[:, 0]\n",
    "    sigma_0_j = samples[:, 1]\n",
    "    lambda_samples_j = samples[:, 2 + j]\n",
    "    lower, upper = np.percentile(lambda_samples_j, [16, 84])\n",
    "    rows.append({\n",
    "        \"Hospital\": j + 1,\n",
    "        \"Reporting frequency\": reporting_frequency[j],\n",
    "        \"16th percentile\": lower,\n",
    "        \"84th percentile\": upper,\n",
    "        \"HPD width (68%)\": upper - lower,\n",
    "        \"mu_0\": np.mean(mu_0_j),\n",
    "        \"sigma_0\": np.mean(sigma_0_j)\n",
    "    })\n",
    "\n",
    "temp = pd.DataFrame(rows)\n",
    "temp = pd.DataFrame(rows).set_index(\"Hospital\")\n",
    "print(temp)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70b92966",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pearson r = -0.874\n",
      "R^2 = 0.764\n",
      "p-value = 9.495e-04\n"
     ]
    }
   ],
   "source": [
    "x = temp[\"Reporting frequency\"].to_numpy()\n",
    "y = temp[\"HPD width (68%)\"].to_numpy()\n",
    "\n",
    "r, p_value = pearsonr(x, y)\n",
    "r_squared = r**2\n",
    "\n",
    "print(f\"Pearson r = {r:.3f}\")\n",
    "print(f\"R^2 = {r_squared:.3f}\")\n",
    "print(f\"p-value = {p_value:.3e}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "74dbf9b4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 38704 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Fit least-squares line\n",
    "slope, intercept = np.polyfit(x, y, 1)\n",
    "x_line = np.linspace(x.min(), x.max(), 100)\n",
    "y_line = slope * x_line + intercept\n",
    "\n",
    "plt.figure()\n",
    "plt.scatter(x, y)\n",
    "plt.plot(x_line, y_line)\n",
    "plt.xlabel(\"Reporting frequency (n_j)\")\n",
    "plt.ylabel(\"HPD width (68%)\")\n",
    "plt.title(\n",
    "    f\"HPD width vs reporting frequency\\n\"\n",
    "    f\"R² = {r_squared:.3f}, r = {r:.2f}, p = {p_value:.3f}\"\n",
    ")\n",
    "plt.show()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
