{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "04fe9429",
            "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": "27bdfcb5",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes",
            "outputs": []
        },
        {
            "id": "61d59651",
            "cell_type": "markdown",
            "source": "Generate some random variates and calculate Box-Cox log-likelihood values\nfor them for a range of ``lmbda`` values:\n",
            "metadata": {}
        },
        {
            "id": "7e611a7b",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "rng = np.random.default_rng()\nx = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng)\nlmbdas = np.linspace(-2, 10)\nllf = np.zeros(lmbdas.shape, dtype=float)\nfor ii, lmbda in enumerate(lmbdas):\n    llf[ii] = stats.boxcox_llf(lmbda, x)",
            "outputs": []
        },
        {
            "id": "74919b51",
            "cell_type": "markdown",
            "source": "Also find the optimal lmbda value with `boxcox`:\n",
            "metadata": {}
        },
        {
            "id": "dd5a0ab7",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "x_most_normal, lmbda_optimal = stats.boxcox(x)",
            "outputs": []
        },
        {
            "id": "ce73d9f6",
            "cell_type": "markdown",
            "source": "Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a\nhorizontal line to check that that's really the optimum:\n",
            "metadata": {}
        },
        {
            "id": "cb6d448a",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "fig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(lmbdas, llf, 'b.-')\nax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r')\nax.set_xlabel('lmbda parameter')\nax.set_ylabel('Box-Cox log-likelihood')",
            "outputs": []
        },
        {
            "id": "50256997",
            "cell_type": "markdown",
            "source": "Now add some probability plots to show that where the log-likelihood is\nmaximized the data transformed with `boxcox` looks closest to normal:\n",
            "metadata": {}
        },
        {
            "id": "20ac4fba",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'\nfor lmbda, loc in zip([-1, lmbda_optimal, 9], locs):\n    xt = stats.boxcox(x, lmbda=lmbda)\n    (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)\n    ax_inset = inset_axes(ax, width=\"20%\", height=\"20%\", loc=loc)\n    ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')\n    ax_inset.set_xticklabels([])\n    ax_inset.set_yticklabels([])\n    ax_inset.set_title(r'$\\lambda=%1.2f$' % lmbda)",
            "outputs": []
        },
        {
            "id": "01b2f105",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "plt.show()",
            "outputs": []
        }
    ]
}