{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e2d16eee",
   "metadata": {},
   "source": [
    "# Kendall's tau test\n",
    "\n",
    "Kendall's tau is a measure of the correspondence between two rankings.\n",
    "\n",
    "Consider the following data from [^1], which studied the relationship between\n",
    "free proline (an amino acid) and total collagen (a protein often found in\n",
    "connective tissue) in unhealthy human livers.\n",
    "\n",
    "The `x` and `y` arrays below record measurements of the two compounds. The\n",
    "observations are paired: each free proline measurement was taken from the same\n",
    "liver as the total collagen measurement at the same index."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bee17cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "# total collagen (mg/g dry weight of liver)\n",
    "x = np.array([7.1, 7.1, 7.2, 8.3, 9.4, 10.5, 11.4])\n",
    "# free proline (μ mole/g dry weight of liver)\n",
    "y = np.array([2.8, 2.9, 2.8, 2.6, 3.5, 4.6, 5.0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4835c0f",
   "metadata": {},
   "source": [
    "These data were analyzed in [^2] using Spearman's correlation coefficient,\n",
    "a statistic similar to Kendall's tau in that it is also sensitive to\n",
    "ordinal correlation between the samples. Let's perform an analogous study\n",
    "using {func}`Kendall's tau <scipy.stats.kendalltau>`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d59faf23",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "res = stats.kendalltau(x, y)\n",
    "res.statistic"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dc28e77",
   "metadata": {},
   "source": [
    "The value of this statistic tends to be high (close to 1) for samples with a\n",
    "strongly positive ordinal correlation, low (close to -1) for samples with a\n",
    "strongly negative ordinal correlation, and small in magnitude (close to zero)\n",
    "for samples with weak ordinal correlation.\n",
    "\n",
    "The test is performed by comparing the observed value of the statistic against\n",
    "the null distribution: the distribution of statistic values derived under the\n",
    "null hypothesis that total collagen and free proline measurements are\n",
    "independent.\n",
    "\n",
    "For this test, the null distribution for large samples without ties is\n",
    "approximated as the normal distribution with variance\n",
    "`(2*(2*n + 5))/(9*n*(n - 1))`, where `n = len(x)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5a140d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "n = len(x)  # len(x) == len(y)\n",
    "var = (2*(2*n + 5))/(9*n*(n - 1))\n",
    "dist = stats.norm(scale=np.sqrt(var))\n",
    "z_vals = np.linspace(-1.25, 1.25, 100)\n",
    "pdf = dist.pdf(z_vals)\n",
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "\n",
    "def plot(ax):  # we'll reuse this\n",
    "    ax.plot(z_vals, pdf)\n",
    "    ax.set_title(\"Kendall Tau Test Null Distribution\")\n",
    "    ax.set_xlabel(\"statistic\")\n",
    "    ax.set_ylabel(\"probability density\")\n",
    "\n",
    "plot(ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58cca6a1",
   "metadata": {},
   "source": [
    "The comparison is quantified by the p-value: the proportion of values in the\n",
    "null distribution as extreme or more extreme than the observed value of the\n",
    "statistic. In a two-sided test in which the statistic is positive, elements of\n",
    "the null distribution greater than the transformed statistic and elements of the\n",
    "null distribution less than the negative of the observed statistic are both\n",
    "considered \"more extreme\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa5d2bbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "plot(ax)\n",
    "pvalue = dist.cdf(-res.statistic) + 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, (0.65, 0.15), (0.8, 0.3), arrowprops=props)\n",
    "i = z_vals >= res.statistic\n",
    "ax.fill_between(z_vals[i], y1=0, y2=pdf[i], color='C0')\n",
    "i = z_vals <= -res.statistic\n",
    "ax.fill_between(z_vals[i], y1=0, y2=pdf[i], color='C0')\n",
    "ax.set_xlim(-1.25, 1.25)\n",
    "ax.set_ylim(0, 0.5)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e663267",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.pvalue"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7c0ca34",
   "metadata": {},
   "source": [
    "Note that there is slight disagreement between the shaded area of the curve and\n",
    "the p-value returned by {func}`scipy.stats.kendalltau`. This is because our data\n",
    "has ties, and we have neglected a tie correction to the null distribution\n",
    "variance that {func}`scipy.stats.kendalltau` performs. For samples without ties,\n",
    "the shaded areas of our plot and p-value returned by\n",
    "{func}`scipy.stats.kendalltau` would match exactly.\n",
    "\n",
    "If the p-value is \"small\" - that is, if there is a low probability of sampling\n",
    "data from independent distributions that produces such an extreme value of the\n",
    "statistic - this may be taken as evidence against the null hypothesis in favor\n",
    "of the alternative: the distribution of total collagen and free proline are\n",
    "*not* independent. 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 [^3] 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",
    "For samples without ties of moderate size, {func}`scipy.stats.kendalltau` can\n",
    "compute the p-value exactly. However, in the presence of ties,\n",
    "{func}`scipy.stats.kendalltau` resorts to an asymptotic approximation.\n",
    "Nonetheless, we can use a permutation test to compute the null distribution\n",
    "exactly: Under the null hypothesis that total collagen and free proline are\n",
    "independent, each of the free proline measurements were equally likely to have\n",
    "been observed with any of the total collagen measurements. Therefore, we can\n",
    "form an *exact* null distribution by calculating the statistic under each\n",
    "possible pairing of elements between `x` and `y`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f95793bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def statistic(x):  # explore all possible pairings by permuting `x`\n",
    "    return stats.kendalltau(x, y).statistic  # ignore pvalue\n",
    "ref = stats.permutation_test((x,), statistic,\n",
    "                             permutation_type='pairings')\n",
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "plot(ax)\n",
    "bins = np.linspace(-1.25, 1.25, 25)\n",
    "ax.hist(ref.null_distribution, bins=bins, density=True)\n",
    "ax.legend(['asymptotic approximation\\n(many observations)',\n",
    "           'exact null distribution'])\n",
    "plot(ax)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2bb8788",
   "metadata": {},
   "outputs": [],
   "source": [
    "ref.pvalue"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d4364ef",
   "metadata": {},
   "source": [
    "Note that there is significant disagreement between the exact p-value calculated\n",
    "here and the approximation returned by {func}`scipy.stats.kendalltau` above. For\n",
    "small samples with ties, consider performing a permutation test for more\n",
    "accurate results.\n",
    "\n",
    "## References\n",
    "\n",
    "[^1]: Kershenobich, D., Fierro, F. J., & Rojkind, M. (1970). The relationship\n",
    "between the free pool of proline and collagen content in human liver cirrhosis.\n",
    "The Journal of Clinical Investigation, 49(12), 2246-2249.\n",
    "[^2]: Hollander, M., Wolfe, D. A., & Chicken, E. (2013). Nonparametric\n",
    "statistical methods. John Wiley & Sons.\n",
    "[^3]: Phipson, B. and Smyth, G. K. (2010). \"Permutation P-values Should Never Be\n",
    "Zero: Calculating Exact P-values When Permutations Are Randomly Drawn.\"\n",
    "Statistical Applications in Genetics and Molecular Biology 9.1."
   ]
  }
 ],
 "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
}
