{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "63f2cb41",
   "metadata": {},
   "source": [
    "# 02402 Week 5\n",
    "\n",
    "Welcome to week 5 of 02402 Statistics (PF)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88fc8695",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import scipy.stats as stats\n",
    "import statsmodels.api as sm     # new library!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6fc65c8f",
   "metadata": {},
   "source": [
    "## Part 1: Example \"voltage drop\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8b8ab0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enter data\n",
    "x = np.array([0.75,-0.85,4.23,2.12,3.04,0.53,-0.35,1.69,1.52,-0.42])\n",
    "\n",
    "# make quick histogram:\n",
    "plt.hist(x)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e8a1384",
   "metadata": {},
   "source": [
    "#### Estimate and confidence interval (+ standard error of the mean)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90870f1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute best estimate for the mean (and the standard error)\n",
    "mean_hat = x.mean()\n",
    "n = len(x)\n",
    "se_mean = x.std(ddof=1)/np.sqrt(n)\n",
    "print([mean_hat, x.std(ddof=1), se_mean])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64181b7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# confidence interval for the mean:\n",
    "mu_lower = mean_hat - stats.t.ppf(0.975, df=9)*se_mean\n",
    "mu_upper = mean_hat + stats.t.ppf(0.975, df=9)*se_mean\n",
    "print([mu_lower, mu_upper])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6594f84",
   "metadata": {},
   "source": [
    "#### Hypothesis test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e59ee154",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the null hypothesis\n",
    "mean_null_hyp = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c909dce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the \"test statistic\" t_obs:\n",
    "tobs = (mean_hat - mean_null_hyp) / se_mean\n",
    "print(tobs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "198e5ee5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# compare with critical values t_0.025 and t_0.975 from t-distribution with df = 9\n",
    "print(stats.t.ppf(0.025, df=n-1))\n",
    "print(stats.t.ppf(0.975, df=n-1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fd494d2",
   "metadata": {},
   "source": [
    "Does the test statistic (t_obs) fall inside this range?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b43e114",
   "metadata": {},
   "source": [
    "#### p-value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04302efc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate p-value\n",
    "2*stats.t.cdf(-tobs, df=n-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03eb81e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# could calculate the same thing in the following way:\n",
    "2*(1 - stats.t.cdf(tobs, df=n-1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01f15720",
   "metadata": {},
   "source": [
    "Can you make a drwing to visualise the p-value as a probability in the t-distribution. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "164e500d",
   "metadata": {},
   "source": [
    "#### Using inbuilt t-test function in Python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7eb4896",
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can also use the ttest_1samp funtion from scipy.stats:\n",
    "print(stats.ttest_1samp(x, popmean=0))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f09b386d",
   "metadata": {},
   "source": [
    "There are several outputs!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5871576",
   "metadata": {},
   "outputs": [],
   "source": [
    "#save all output in a variable:\n",
    "output = stats.ttest_1samp(x, popmean=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d206355",
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the different outputs, by specifying which one:\n",
    "\n",
    "print(output.pvalue)\n",
    "\n",
    "print(output.statistic)\n",
    "\n",
    "print(output.df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61e6a1ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "# the function \"ttest_1samp\" can also compute confidence intervals:\n",
    "print(stats.ttest_1samp(x, popmean=0).confidence_interval(confidence_level=0.95))\n",
    "print(stats.ttest_1samp(x, popmean=0).confidence_interval(confidence_level=0.99))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "987f7056",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(output.confidence_interval(confidence_level=0.95))\n",
    "print(output.confidence_interval(confidence_level=0.99))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abe4110a",
   "metadata": {},
   "source": [
    "## Part 2: Simulation and QQ-plot\n",
    "\n",
    "### Simulation: \n",
    "We simulate a lot of small samples (n=10) from a known normal distribution. Then we expect if the sample \"looks normal\". "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55af8038",
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(24)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6c55bac",
   "metadata": {},
   "outputs": [],
   "source": [
    "# population parameters:\n",
    "mu = 100\n",
    "sigma = 12\n",
    "\n",
    "# simulated sample:\n",
    "n = 10\n",
    "\n",
    "# significance level (for plotting confidence interval of the mean)\n",
    "a = 0.05\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a59814c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Simulation (repeat this cell many times)\n",
    "data = stats.norm.rvs(mu, sigma, size=n)\n",
    "\n",
    "fig, axs = plt.subplots(1, 1, figsize=(10/3,4))\n",
    "\n",
    "# plot histogram\n",
    "axs.hist(data, density=True, bins=6)\n",
    "axs.set_xlim([70,130])\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abcd18b7",
   "metadata": {},
   "source": [
    "The histogram of the sample does not always look very \"normal\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89ce4224",
   "metadata": {},
   "source": [
    "### ECDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef145d9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(24)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c162aac2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (repeat this cell many times)\n",
    "data = stats.norm.rvs(mu, sigma, size=n)\n",
    "\n",
    "# split plot in 2 \n",
    "fig, axs = plt.subplots(1, 2, figsize=(10*2/3,4))\n",
    "\n",
    "# plot histogram\n",
    "axs[0].hist(data, density=True, bins=6)\n",
    "axs[0].set_xlim([70,130])\n",
    "\n",
    "# plot ecdf\n",
    "axs[1].ecdf(data)\n",
    "axs[1].plot(np.arange(70,130,1), stats.norm.cdf(np.arange(70,130,1), loc=mu, scale=sigma))\n",
    "axs[1].set_xlim([70,130])\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf428e9b",
   "metadata": {},
   "source": [
    "### Q-Q plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "545a754a",
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(24)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c13cc996",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (repeat this cell many times)\n",
    "data = stats.norm.rvs(mu, sigma, size=n)\n",
    "\n",
    "# split plot in 3\n",
    "fig, axs = plt.subplots(1, 3, figsize=(10,4))\n",
    "\n",
    "# plot histogram\n",
    "axs[0].hist(data, density=True, bins=6)\n",
    "axs[0].set_xlim([70,130])\n",
    "\n",
    "# plot ecdf\n",
    "axs[1].ecdf(data)\n",
    "axs[1].plot(np.arange(70,130,1), stats.norm.cdf(np.arange(70,130,1), loc=mu, scale=sigma))\n",
    "axs[1].set_xlim([70,130])\n",
    "\n",
    "# plot qq-plot\n",
    "sm.qqplot(data,line=\"q\",a=3/8,ax=axs[2])\n",
    "# OBS: \"a = 3/8\" is preferred for n <= 10 \n",
    "#     (\"a = 1/2\" is preferred for n >  10)  \n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef36ff49",
   "metadata": {},
   "source": [
    "(back to slides)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecaea6b5",
   "metadata": {},
   "source": [
    "### Larger samples and different distributions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03f7723b",
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(24)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a16dc51d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# (repeat this cell many times)\n",
    "\n",
    "n = 100 # larger sample size\n",
    "data = stats.norm.rvs(mu, sigma, size=n)\n",
    "\n",
    "# split plot in 3\n",
    "fig, axs = plt.subplots(1, 3, figsize=(10,4))\n",
    "\n",
    "# plot histogram\n",
    "axs[0].hist(data, density=True)\n",
    "axs[0].set_xlim([70,130])\n",
    "\n",
    "# plot ecdf\n",
    "axs[1].ecdf(data)\n",
    "axs[1].plot(np.arange(70,130,1), stats.norm.cdf(np.arange(70,130,1), loc=mu, scale=sigma))\n",
    "axs[1].set_xlim([70,130])\n",
    "\n",
    "# plot qq-plot\n",
    "sm.qqplot(data,line=\"q\",a=1/2,ax=axs[2])\n",
    "# OBS: \"a = 3/8\" is preferred for n <= 10 \n",
    "#     (\"a = 1/2\" is preferred for n >  10)  \n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2712d4e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# examples with exponentially distributed data:\n",
    "\n",
    "n = 100 # try both n=10 and n=100\n",
    "data = stats.expon.rvs(mu, sigma, size=n)\n",
    "fig, axs = plt.subplots(1, 3, figsize=(10,4))\n",
    "axs[0].hist(data, density=True)\n",
    "axs[1].ecdf(data)\n",
    "axs[1].plot(np.arange(70,150,1), stats.norm.cdf(np.arange(70,150,1), loc=stats.expon.mean(loc=mu, scale=sigma), scale=stats.expon.std(loc=mu, scale=sigma)))\n",
    "axs[1].set_xlim(70,150)\n",
    "sm.qqplot(data,line=\"q\",a=1/2,ax=axs[2])\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9afd5a65",
   "metadata": {},
   "outputs": [],
   "source": [
    "# examples with uniformly distributed data:\n",
    "\n",
    "n = 10 # try both n=10 and n=100\n",
    "data = stats.uniform.rvs(mu, sigma, size=n)\n",
    "fig, axs = plt.subplots(1, 3, figsize=(10,4))\n",
    "axs[0].hist(data, density=True)\n",
    "axs[1].ecdf(data)\n",
    "axs[1].plot(np.arange(90,120,1), stats.norm.cdf(np.arange(90,120,1), loc=stats.uniform.mean(loc=mu, scale=sigma), scale=stats.uniform.std(loc=mu, scale=sigma)))\n",
    "axs[1].set_xlim(90,120)\n",
    "sm.qqplot(data,line=\"q\",a=1/2,ax=axs[2])\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pernille",
   "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.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
