{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "be915d56-9a8a-422b-9da4-d7ca37dd0b85",
   "metadata": {
    "id": "be915d56-9a8a-422b-9da4-d7ca37dd0b85"
   },
   "source": [
    "# Bayesian modelling\n",
    "\n",
    "Gamma and betaprime distribution:\n",
    "\n",
    "Ref:\n",
    "  * https://docs.scipy.org/doc/scipy/tutorial/stats/continuous_gamma.html\n",
    "  * https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.betaprime.html"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9aacace",
   "metadata": {},
   "source": [
    "## Common"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0ade8aaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import scipy\n",
    "import pandas as pd\n",
    "\n",
    "import os\n",
    "\n",
    "import data_utils\n",
    "import bayesian"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6fa3ccb1-05c0-4ab9-a74a-a4e20d1e38f8",
   "metadata": {
    "id": "6fa3ccb1-05c0-4ab9-a74a-a4e20d1e38f8"
   },
   "source": [
    "## Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c72c613c",
   "metadata": {
    "executionInfo": {
     "elapsed": 2756,
     "status": "ok",
     "timestamp": 1715067840744,
     "user": {
      "displayName": "Marija Delić",
      "userId": "03427129792104028391"
     },
     "user_tz": -120
    },
    "id": "c72c613c",
    "tags": []
   },
   "outputs": [],
   "source": [
    "results_path = \"./results\"\n",
    "if not os.path.exists(results_path): os.makedirs(results_path)\n",
    "\n",
    "data_path = \"../../data/\"\n",
    "suv_filename = os.path.join(data_path, \"suv_percentilesSLOthenUWM.mat\")\n",
    "flags_filename = os.path.join(data_path,\"flags_combined.mat\")\n",
    "normal_range_filename = os.path.join(data_path, \"normal_range.mat\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f5ffd7f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Loading all data\n",
    "\"\"\"\n",
    "suv_dict = scipy.io.loadmat(suv_filename)\n",
    "flags_dict = scipy.io.loadmat(flags_filename)\n",
    "normal_range_dict = scipy.io.loadmat(normal_range_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4dbb2f49",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "odds = 0.09433962264150944\n",
      "ns = [53, 5]\n"
     ]
    }
   ],
   "source": [
    "# get data\n",
    "perc = 95\n",
    "organ = \"lung\"\n",
    "\n",
    "x, y = data_utils.get_data(organ, perc, suv_dict, flags_dict)\n",
    "odds = len(x[y == 1])/len(x[y == 0])  # Prob(Y=1)/Prob(Y=0)\n",
    "xs = [x[y == i] for i in range(2)]\n",
    "ns = [len(e) for e in xs]\n",
    "\n",
    "print(f\"{odds = }\")\n",
    "print(f\"{ns = }\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c4a5c84-c72a-4b48-a92c-7e25f5b752fc",
   "metadata": {
    "id": "8c4a5c84-c72a-4b48-a92c-7e25f5b752fc"
   },
   "source": [
    "## Explore data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9879854b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0:(1.3076106366121545, 0.25845619452679225)\n",
      "1:(2.451199436187744, 0.870810277632464)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 44380 characters]",
      "text/plain": [
       "<Figure size 1200x500 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\"\"\"\n",
    "    Explore if data can be fitted by normal distribution\n",
    "\"\"\"\n",
    "# compare fit in plt\n",
    "fig, axs = plt.subplots(ncols = 2, figsize=(6*2,5))\n",
    "\n",
    "for i, (e, ax) in enumerate(zip(xs, axs)):\n",
    "    distr = scipy.stats.norm\n",
    "    \n",
    "    # fit on full parameter space\n",
    "    pars_single = distr.fit(e)\n",
    "    print(f\"{i}:{pars_single}\")\n",
    "\n",
    "    # compare fit and data histogram\n",
    "    t = np.linspace(min(e), max(e), 100)\n",
    "\n",
    "    ax.hist(e, density = True, label = \"data\")\n",
    "    ax.plot(t, distr.pdf(t, *pars_single), label = \"fit\")\n",
    "    \n",
    "    ax.set_title(f\"group:{i}\")\n",
    "    ax.legend()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ad55fcd6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0: (90.02975828622073, 45.40365710465922, -0.0405464844490462, 0.6646700878664)\n",
      "1: (12.71805692599693, 2.2588421497667177, 1.4442107848868178, 0.1068382446393942)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 45700 characters]",
      "text/plain": [
       "<Figure size 1200x500 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\"\"\"\n",
    "    Explore if data can be fitted by normal distribution\n",
    "\"\"\"\n",
    "# compare fit in plt\n",
    "fig, axs = plt.subplots(ncols = 2, figsize=(6*2,5))\n",
    "\n",
    "for i, (e, ax) in enumerate(zip(xs, axs)):\n",
    "    distr = scipy.stats.betaprime\n",
    "    \n",
    "    # fit on full parameter space\n",
    "    pars_single = distr.fit(e)\n",
    "    print(f\"{i}: {pars_single}\")\n",
    "\n",
    "    # compare fit and data histogram\n",
    "    t = np.linspace(min(e)*1.1, max(e), 100)\n",
    "\n",
    "    ax.hist(e, density = True, label = \"data\")\n",
    "    ax.plot(t, distr.pdf(t, *pars_single), label = \"fit\")\n",
    "    \n",
    "    ax.set_title(f\"group:{i}\")\n",
    "    ax.legend()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c32485f8",
   "metadata": {},
   "source": [
    "## Normal distribution"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a29519f9",
   "metadata": {},
   "source": [
    "### Fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "081c152b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# for testing define distribution we want to use\n",
    "# normal is not a good distribution!\n",
    "distr_str = \"scipy.stats.norm\"\n",
    "\n",
    "# define logarithm of pdfs used on the Bayesian model\n",
    "bounds = [\n",
    "            [(0.1, 100), (0.1, 100)],   # group 0\n",
    "            [(0.1, 100), (0.1, 100)]    # group 1\n",
    "          ]\n",
    "\n",
    "# parsing parameters\n",
    "parse_pars = lambda pars: dict(loc = pars[0], scale = pars[1])\n",
    "\n",
    "# define function related to chosen distribution\n",
    "log_pdfs,distr_sample = bayesian.setup_scipy_distr(distr_str, 2, parse_pars)\n",
    "\n",
    "# define Bayesian model instance\n",
    "BM = bayesian.BayesianModelRegression\n",
    "bm = BM(odds, log_pdfs, bounds, distr_sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "46484c9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# doing the fit\n",
    "res_fit = bm.fit(x,y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "fa5fa70e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "LLF",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "AIC",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "BIC",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "A",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "chi2",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "p-value(chi2)",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "n",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "k",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "dof",
         "rawType": "int64",
         "type": "integer"
        }
       ],
       "ref": "4d5418c3-36ca-46c4-b408-d197447de6c9",
       "rows": [
        [
         "0",
         "-6.684329291238636",
         "21.368658582477273",
         "29.610430624662946",
         "0.9655172413793104",
         "19.73899320013926",
         "0.9999949020267289",
         "58",
         "4",
         "54"
        ]
       ],
       "shape": {
        "columns": 9,
        "rows": 1
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>LLF</th>\n",
       "      <th>AIC</th>\n",
       "      <th>BIC</th>\n",
       "      <th>A</th>\n",
       "      <th>chi2</th>\n",
       "      <th>p-value(chi2)</th>\n",
       "      <th>n</th>\n",
       "      <th>k</th>\n",
       "      <th>dof</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-6.684329</td>\n",
       "      <td>21.368659</td>\n",
       "      <td>29.610431</td>\n",
       "      <td>0.965517</td>\n",
       "      <td>19.738993</td>\n",
       "      <td>0.999995</td>\n",
       "      <td>58</td>\n",
       "      <td>4</td>\n",
       "      <td>54</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        LLF        AIC        BIC         A       chi2  p-value(chi2)   n  k  \\\n",
       "0 -6.684329  21.368659  29.610431  0.965517  19.738993       0.999995  58  4   \n",
       "\n",
       "   dof  \n",
       "0   54  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# table of goodness of fit measures\n",
    "pd.DataFrame([bm.goodness_of_fit(x, y, res_fit[\"pars\"])])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "46717697",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30776 characters]",
      "text/plain": [
       "<Figure size 700x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plotting fit and data\n",
    "fig, ax = plt.subplots(figsize=(7,5))\n",
    "\n",
    "# plot input data\n",
    "for i, lab in zip(np.arange(2), [\"NC\", \"AE\"]):\n",
    "    ax.scatter(x[y == i], y[y == i], label = lab, zorder = 2.5)\n",
    "\n",
    "# plotting optimal model\n",
    "xp = np.linspace(min(x), max(x), 100)\n",
    "ax.plot(xp, bm.model(xp, res_fit[\"pars\"]), label = \"fit\")\n",
    "\n",
    "ax.set_xlabel(r\"$x = max_{visit} SUV(visit, p)$\")\n",
    "ax.set_ylabel(\"P(AE|X = x)\")\n",
    "\n",
    "ax.legend()\n",
    "\n",
    "plt.savefig(os.path.join(results_path, \"bayesian_fit.pdf\"))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a974ab00-e992-4de8-8a9f-431264fe376a",
   "metadata": {
    "id": "a974ab00-e992-4de8-8a9f-431264fe376a"
   },
   "source": [
    "### CI of models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8386c0d0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "boots:get_nonparam_boots_pars\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/horvat/Documents/work/medfiz/git/uncertainty_study/python/bayesian/bayesian.py:142: RuntimeWarning: overflow encountered in exp\n",
      "  return np.sum(np.log(1 + np.exp(-S*F)))\n",
      "/home/horvat/venvs/base/lib/python3.12/site-packages/scipy/optimize/_numdiff.py:592: RuntimeWarning: invalid value encountered in subtract\n",
      "  df = fun(x1) - f0\n"
     ]
    }
   ],
   "source": [
    "# nr. of bootstrapped samples\n",
    "Nboots = 10**4\n",
    "\n",
    "labs = [\"non-param\", \n",
    "        \"non-param strat\", \n",
    "        \"param\", \n",
    "        \"param strat\"]\n",
    "\n",
    "funs = [\"get_nonparam_boots_pars\",\n",
    "        \"get_nonparam_strat_boots_pars\", \n",
    "        \"get_param_boots_pars\",\n",
    "        \"get_param_strat_boots_pars\"]\n",
    "\n",
    "# defining twosided probabilities\n",
    "alpha = 0.05   # significance level\n",
    "probs = [alpha/2, 1 - alpha/2]\n",
    "\n",
    "# calculate bootstrapped parameters\n",
    "dict_bpars = dict()\n",
    "\n",
    "for lab, fun in zip(labs, funs):\n",
    "    print(f\"boots:{fun}\")\n",
    "    \n",
    "    # define bootstrapping function \n",
    "    qm = eval(f\"bm.{fun}\")\n",
    "    \n",
    "    # do bootstrapping\n",
    "    dict_bpars[lab] = qm(x, y, Nboots)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "506a1d8d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "non-param:\n",
      "  isnan: []\n",
      "  isinf: []\n",
      "non-param strat:\n",
      "  isnan: []\n",
      "  isinf: []\n",
      "param:\n",
      "  isnan: []\n",
      "  isinf: []\n",
      "param strat:\n",
      "  isnan: []\n",
      "  isinf: []\n"
     ]
    }
   ],
   "source": [
    "# checking if we have strange parameters\n",
    "for lab, bpars in dict_bpars.items():\n",
    "    print(f\"{lab}:\")\n",
    "    print(\"  isnan:\", [p for p in bpars if np.isnan(p).any()])\n",
    "    print(\"  isinf:\", [p for p in bpars if np.isinf(p).any()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95681175",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 57988 characters]",
      "text/plain": [
       "<Figure size 700x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plotting fit and data\n",
    "fig, ax = plt.subplots(figsize=(7,5))\n",
    "\n",
    "# plot input data\n",
    "for i, lab in zip(np.arange(2), [\"NC\", \"AE\"]):\n",
    "    ax.scatter(x[y == i], y[y == i], label = lab, zorder = 2.5)\n",
    "\n",
    "# plotting optimal model\n",
    "xp = np.linspace(min(x), max(x), 100)\n",
    "ax.plot(xp, bm.model(xp, res_fit[\"pars\"]), label = \"fit\")\n",
    "\n",
    "# plotting CI\n",
    "for lab, bpars in dict_bpars.items():\n",
    "\n",
    "    # calculate model values of for all bootstrapped parameters\n",
    "    model_values = [bm.model(xp, p) for p in bpars]\n",
    "    qs = np.quantile(model_values, probs, axis = 0)\n",
    "\n",
    "    # make plot of quantiles\n",
    "    ax.fill_between(xp, *qs, alpha = 0.2, label = f\"CI:{lab}\")\n",
    "\n",
    "ax.set_xlabel(r\"$x = max_{visit} SUV(visit, p)$\")\n",
    "ax.set_ylabel(\"P(AE|X = x)\")\n",
    "\n",
    "ax.legend()\n",
    "\n",
    "plt.savefig(os.path.join(results_path, \"bayesian_CI_cmp.pdf\"))\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dd3fe2a",
   "metadata": {},
   "source": [
    "## X distribution"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c24028c4",
   "metadata": {},
   "source": [
    "### Fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1248787c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# for testing define distribution we want to use\n",
    "distr_str = \"scipy.stats.betaprime\"\n",
    "\n",
    "# define logarithm of pdfs used on the Bayesian model\n",
    "bounds = [\n",
    "            [(1e-3, 100), (1e-3, 100),(1e-3, 100)],   # group 0\n",
    "            [(1e-3, 100), (1e-3, 100), (1e-3, 100)]    # group 1\n",
    "          ]\n",
    "\n",
    "# parsing parameters\n",
    "parse_pars = lambda pars: dict(a = pars[0], b = pars[1], scale  =pars[2])\n",
    "\n",
    "# define function related to chosen distribution\n",
    "log_pdfs,distr_sample = bayesian.setup_scipy_distr(\"scipy.stats.betaprime\", 3, parse_pars)\n",
    "\n",
    "# define Bayesian model instance\n",
    "BM = bayesian.BayesianModelRegression\n",
    "bm = BM(odds, log_pdfs, bounds, distr_sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3fcebc3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# doing the fit\n",
    "res_fit = bm.fit(x,y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a85bf04",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'pars': array([7.73632853e+01, 1.29956893e+00, 1.25838773e-03, 1.00000000e+02,\n",
       "        2.34611352e+01, 6.96714486e-01]),\n",
       " 'success': True,\n",
       " 'cost': 5.940406766675263}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res_fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b257da7f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "LLF",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "AIC",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "BIC",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "A",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "chi2",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "p-value(chi2)",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "n",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "k",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "dof",
         "rawType": "int64",
         "type": "integer"
        }
       ],
       "ref": "1625f89b-fb61-4149-9457-a7002bfbee02",
       "rows": [
        [
         "0",
         "-5.940406766675263",
         "23.880813533350526",
         "36.24347159662904",
         "0.9655172413793104",
         "14.908459605685204",
         "0.9999999050029449",
         "58",
         "6",
         "52"
        ]
       ],
       "shape": {
        "columns": 9,
        "rows": 1
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>LLF</th>\n",
       "      <th>AIC</th>\n",
       "      <th>BIC</th>\n",
       "      <th>A</th>\n",
       "      <th>chi2</th>\n",
       "      <th>p-value(chi2)</th>\n",
       "      <th>n</th>\n",
       "      <th>k</th>\n",
       "      <th>dof</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-5.940407</td>\n",
       "      <td>23.880814</td>\n",
       "      <td>36.243472</td>\n",
       "      <td>0.965517</td>\n",
       "      <td>14.90846</td>\n",
       "      <td>1.0</td>\n",
       "      <td>58</td>\n",
       "      <td>6</td>\n",
       "      <td>52</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        LLF        AIC        BIC         A      chi2  p-value(chi2)   n  k  \\\n",
       "0 -5.940407  23.880814  36.243472  0.965517  14.90846            1.0  58  6   \n",
       "\n",
       "   dof  \n",
       "0   52  "
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# table of goodness of fit measures\n",
    "pd.DataFrame([bm.goodness_of_fit(x, y, res_fit[\"pars\"])])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57a50c56",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30336 characters]",
      "text/plain": [
       "<Figure size 700x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plotting fit and data\n",
    "fig, ax = plt.subplots(figsize=(7,5))\n",
    "\n",
    "# plot input data\n",
    "for i, lab in zip(np.arange(2), [\"NC\", \"AE\"]):\n",
    "    ax.scatter(x[y == i], y[y == i], label = lab, zorder = 2.5)\n",
    "\n",
    "# plotting optimal model\n",
    "xp = np.linspace(min(x), max(x), 100)\n",
    "ax.plot(xp, bm.model(xp, res_fit[\"pars\"]), label = \"fit\")\n",
    "\n",
    "ax.set_xlabel(r\"$x = max_{visit} SUV(visit, p)$\")\n",
    "ax.set_ylabel(\"P(AE|X = x)\")\n",
    "\n",
    "ax.legend()\n",
    "\n",
    "plt.savefig(os.path.join(results_path, \"bayesian_fit.pdf\"))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68f4ee1c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "base",
   "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.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
