{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "719202a5",
            "cell_type": "markdown",
            "source": "<div class='alert alert-warning'>\n\nSciPy's interactive examples with Jupyterlite are experimental and may not always work as expected. Execution of cells containing imports may result in large downloads (up to 60MB of content for the first import from SciPy). Load times when importing from SciPy may take roughly 10-20 seconds. If you notice any problems, feel free to open an [issue](https://github.com/scipy/scipy/issues/new/choose).\n\n</div>",
            "metadata": {}
        },
        {
            "id": "8b610828",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nfrom scipy.special import smirnov\nfrom scipy.stats import norm",
            "outputs": []
        },
        {
            "id": "7251416c",
            "cell_type": "markdown",
            "source": "Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a\nsample of size 5.\n",
            "metadata": {}
        },
        {
            "id": "1948e779",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "smirnov(5, [0, 0.5, 1.0])",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "array([ 1.   ,  0.056,  0.   ])"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "a1b25789",
            "cell_type": "markdown",
            "source": "Compare a sample of size 5 against N(0, 1), the standard normal\ndistribution with mean 0 and standard deviation 1.\n\n`x` is the sample.\n",
            "metadata": {}
        },
        {
            "id": "c303ff48",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])",
            "outputs": []
        },
        {
            "id": "c1545da1",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "target = norm(0, 1)\ncdfs = target.cdf(x)\ncdfs",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "588eaf98",
            "cell_type": "markdown",
            "source": "Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).\n",
            "metadata": {}
        },
        {
            "id": "969524df",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "n = len(x)\necdfs = np.arange(n+1, dtype=float)/n\ncols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],\n                       ecdfs[1:] - cdfs])\nwith np.printoptions(precision=3):\n   print(cols)",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "[[-1.392  0.2    0.082  0.082  0.118]\n [-0.135  0.4    0.446  0.246 -0.046]\n [ 0.114  0.6    0.545  0.145  0.055]\n [ 0.19   0.8    0.575 -0.025  0.225]\n [ 1.82   1.     0.966  0.166  0.034]]"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "9fc108de",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "gaps = cols[:, -2:]\nDnpm = np.max(gaps, axis=0)\nprint(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "Dn-=0.246306, Dn+=0.224655"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "99595c72",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "probs = smirnov(n, Dnpm)\nprint(f'For a sample of size {n} drawn from N(0, 1):',\n      f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',\n      f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',\n      sep='\\n')",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "For a sample of size 5 drawn from N(0, 1):\n Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711\n Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "f3c3bb38",
            "cell_type": "markdown",
            "source": "Plot the empirical CDF and the standard normal CDF.\n",
            "metadata": {}
        },
        {
            "id": "f2f30a5d",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import matplotlib.pyplot as plt\nplt.step(np.concatenate(([-2.5], x, [2.5])),\n         np.concatenate((ecdfs, [1])),\n         where='post', label='Empirical CDF')\nxx = np.linspace(-2.5, 2.5, 100)\nplt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')",
            "outputs": []
        },
        {
            "id": "77660a94",
            "cell_type": "markdown",
            "source": "Add vertical lines marking Dn+ and Dn-.\n",
            "metadata": {}
        },
        {
            "id": "9d8ff944",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "iminus, iplus = np.argmax(gaps, axis=0)\nplt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',\n           alpha=0.5, lw=4)\nplt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',\n           alpha=0.5, lw=4)",
            "outputs": []
        },
        {
            "id": "b4ea289d",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "plt.grid(True)\nplt.legend(framealpha=1, shadow=True)\nplt.show()",
            "outputs": []
        }
    ]
}