{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d33eb149",
   "metadata": {},
   "source": [
    "# Fligner-Killeen test for equality of variance\n",
    "\n",
    "In [^1], the influence of vitamin C on the tooth growth of guinea pigs was\n",
    "investigated. In a control study, 60 subjects were divided into small dose,\n",
    "medium dose, and large dose groups that received daily doses of 0.5, 1.0 and\n",
    "2.0 mg of vitamin C, respectively. After 42 days, the tooth growth was measured.\n",
    "\n",
    "The `small_dose`, `medium_dose`, and `large_dose` arrays below record\n",
    "tooth growth measurements of the three groups in microns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b950faba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "small_dose = np.array([\n",
    "    4.2, 11.5, 7.3, 5.8, 6.4, 10, 11.2, 11.2, 5.2, 7,\n",
    "    15.2, 21.5, 17.6, 9.7, 14.5, 10, 8.2, 9.4, 16.5, 9.7\n",
    "])\n",
    "medium_dose = np.array([\n",
    "    16.5, 16.5, 15.2, 17.3, 22.5, 17.3, 13.6, 14.5, 18.8, 15.5,\n",
    "    19.7, 23.3, 23.6, 26.4, 20, 25.2, 25.8, 21.2, 14.5, 27.3\n",
    "])\n",
    "large_dose = np.array([\n",
    "    23.6, 18.5, 33.9, 25.5, 26.4, 32.5, 26.7, 21.5, 23.3, 29.5,\n",
    "    25.5, 26.4, 22.4, 24.5, 24.8, 30.9, 26.4, 27.3, 29.4, 23\n",
    "])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92c70a1b",
   "metadata": {},
   "source": [
    "The Fligner-Killeen statistic ({func}`scipy.stats.fligner`) is sensitive to\n",
    "differences in variances between the samples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a83906b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "res = stats.fligner(small_dose, medium_dose, large_dose)\n",
    "res.statistic"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6399d285",
   "metadata": {},
   "source": [
    "The value of the statistic tends to be high when there is a large difference in\n",
    "variances.\n",
    "\n",
    "We can test for inequality of variance among the groups by comparing the\n",
    "observed value of the statistic against the null distribution: the distribution\n",
    "of statistic values derived under the null hypothesis that the population\n",
    "variances of the three groups are equal.\n",
    "\n",
    "For this test, the null distribution follows the\n",
    "{ref}`chi-square distribution <continuous-chi2>` as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b097171e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "k = 3  # number of samples\n",
    "dist = dist = stats.chi2(df=k-1)\n",
    "val = np.linspace(0, 8, 100)\n",
    "pdf = dist.pdf(val)\n",
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "\n",
    "def plot(ax):  # we'll reuse this\n",
    "    ax.plot(val, pdf, color='C0')\n",
    "    ax.set_title(\"Fligner Test Null Distribution\")\n",
    "    ax.set_xlabel(\"statistic\")\n",
    "    ax.set_ylabel(\"probability density\")\n",
    "    ax.set_xlim(0, 8)\n",
    "    ax.set_ylim(0, 0.5)\n",
    "\n",
    "plot(ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "383bd0e2",
   "metadata": {},
   "source": [
    "The comparison is quantified by the p-value: the proportion of values in the\n",
    "null distribution greater than or equal to the observed value of the statistic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "484297d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "plot(ax)\n",
    "pvalue = dist.sf(res.statistic)\n",
    "annotation = (f'p-value={pvalue:.4f}\\n(shaded area)')\n",
    "props = dict(facecolor='black', width=1, headwidth=5, headlength=8)\n",
    "_ = ax.annotate(annotation, (1.5, 0.22), (2.25, 0.3), arrowprops=props)\n",
    "i = val >= res.statistic\n",
    "ax.fill_between(val[i], y1=0, y2=pdf[i], color='C0')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aff6b228",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.pvalue"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab9be9ec",
   "metadata": {},
   "source": [
    "If the p-value is \"small\" - that is, if there is a low probability of sampling\n",
    "data from distributions with identical variances that produces such an extreme\n",
    "value of the statistic - this may be taken as evidence against the null\n",
    "hypothesis in favor of the alternative: the variances of the groups are not\n",
    "equal. Note that:\n",
    "\n",
    "- The inverse is not true; that is, the test is not used to provide\n",
    "  evidence for the null hypothesis.\n",
    "- The threshold for values that will be considered \"small\" is a choice that\n",
    "  should be made before the data is analyzed [^2] with consideration of the\n",
    "  risks of both false positives (incorrectly rejecting the null hypothesis)\n",
    "  and false negatives (failure to reject a false null hypothesis).\n",
    "- Small p-values are not evidence for a *large* effect; rather, they can\n",
    "  only provide evidence for a \"significant\" effect, meaning that they are\n",
    "  unlikely to have occurred under the null hypothesis.\n",
    "\n",
    "Note that the chi-square distribution provides an asymptotic approximation of\n",
    "the null distribution. For small samples, it may be more appropriate to perform\n",
    "a permutation test: Under the null hypothesis that all three samples were drawn\n",
    "from the same population, each of the measurements is equally likely to have\n",
    "been observed in any of the three samples. Therefore, we can form a randomized\n",
    "null distribution by calculating the statistic under many randomly-generated\n",
    "partitionings of the observations into the three samples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9d888ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "def statistic(*samples):\n",
    "    return stats.fligner(*samples).statistic\n",
    "ref = stats.permutation_test(\n",
    "    (small_dose, medium_dose, large_dose), statistic,\n",
    "    permutation_type='independent', alternative='greater'\n",
    ")\n",
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "plot(ax)\n",
    "bins = np.linspace(0, 8, 25)\n",
    "ax.hist(\n",
    "    ref.null_distribution, bins=bins, density=True, facecolor=\"C1\"\n",
    ")\n",
    "ax.legend(['asymptotic approximation\\n(many observations)',\n",
    "           'randomized null distribution'])\n",
    "plot(ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d3e83c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "ref.pvalue  # randomized test p-value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1eb9e090",
   "metadata": {},
   "source": [
    "Note that there is significant disagreement between the p-value calculated here\n",
    "and the asymptotic approximation returned by {func}`scipy.stats.fligner` above.\n",
    "The statistical inferences that can be drawn rigorously from a permutation test\n",
    "are limited; nonetheless, they may be the preferred approach in many\n",
    "circumstances [^3].\n",
    "\n",
    "## References\n",
    "\n",
    "[^1]: Bliss, C.I. (1952), The Statistics of Bioassay: With Special Reference to\n",
    "the Vitamins, pp 499-503. {doi}`10.1016/C2013-0-12584-6`\n",
    "[^2]: Phipson, B. and Smyth, G. K. (2010) \"Permutation P-values Should Never Be Zero:\n",
    "Calculating Exact P-values When Permutations Are Randomly Drawn.\" Statistical\n",
    "Applications in Genetics and Molecular Biology 9.1.\n",
    "[^3]: Ludbrook, J., & Dudley, H. (1998). Why permutation tests are superior to\n",
    "t and F tests in biomedical research. The American Statistician, 52(2), 127-132."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "text_representation": {
    "extension": ".md",
    "format_name": "myst",
    "format_version": 0.13,
    "jupytext_version": "1.16.1"
   }
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
