{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "863f0d70",
            "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": "77bf20ae",
            "cell_type": "markdown",
            "source": "We can compare the window to `kaiser`, which was invented as an alternative\nthat was easier to calculate [3] (example adapted from\n[here](https://ccrma.stanford.edu/~jos/sasp/Kaiser_DPSS_Windows_Compared.html)):\n",
            "metadata": {}
        },
        {
            "id": "047de532",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import windows, freqz\nM = 51\nfig, axes = plt.subplots(3, 2, figsize=(5, 7))\nfor ai, alpha in enumerate((1, 3, 5)):\n    win_dpss = windows.dpss(M, alpha)\n    beta = alpha*np.pi\n    win_kaiser = windows.kaiser(M, beta)\n    for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')):\n        win /= win.sum()\n        axes[ai, 0].plot(win, color=c, lw=1.)\n        axes[ai, 0].set(xlim=[0, M-1], title=rf'$\\alpha$ = {alpha}',\n                        ylabel='Amplitude')\n        w, h = freqz(win)\n        axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.)\n        axes[ai, 1].set(xlim=[0, np.pi],\n                        title=rf'$\\beta$ = {beta:0.2f}',\n                        ylabel='Magnitude (dB)')\nfor ax in axes.ravel():\n    ax.grid(True)\naxes[2, 1].legend(['DPSS', 'Kaiser'])\nfig.tight_layout()\nplt.show()",
            "outputs": []
        },
        {
            "id": "08c361e7",
            "cell_type": "markdown",
            "source": "And here are examples of the first four windows, along with their\nconcentration ratios:\n",
            "metadata": {}
        },
        {
            "id": "bf6940ba",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "M = 512\nNW = 2.5\nwin, eigvals = windows.dpss(M, NW, 4, return_ratios=True)\nfig, ax = plt.subplots(1)\nax.plot(win.T, linewidth=1.)\nax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples',\n       title=f'DPSS, {M:d}, {NW:0.1f}')\nax.legend([f'win[{ii}] ({ratio:0.4f})'\n           for ii, ratio in enumerate(eigvals)])\nfig.tight_layout()\nplt.show()",
            "outputs": []
        },
        {
            "id": "233f112c",
            "cell_type": "markdown",
            "source": "Using a standard $l_{\\infty}$ norm would produce two unity values\nfor even `M`, but only one unity value for odd `M`. This produces uneven\nwindow power that can be counteracted by the approximate correction\n``M**2/float(M**2+NW)``, which can be selected by using\n``norm='approximate'`` (which is the same as ``norm=None`` when\n``Kmax=None``, as is the case here). Alternatively, the slower\n``norm='subsample'`` can be used, which uses subsample shifting in the\nfrequency domain (FFT) to compute the correction:\n",
            "metadata": {}
        },
        {
            "id": "7a199f4c",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "Ms = np.arange(1, 41)\nfactors = (50, 20, 10, 5, 2.0001)\nenergy = np.empty((3, len(Ms), len(factors)))\nfor mi, M in enumerate(Ms):\n    for fi, factor in enumerate(factors):\n        NW = M / float(factor)\n        # Corrected using empirical approximation (default)\n        win = windows.dpss(M, NW)\n        energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M)\n        # Corrected using subsample shifting\n        win = windows.dpss(M, NW, norm='subsample')\n        energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M)\n        # Uncorrected (using l-infinity norm)\n        win /= win.max()\n        energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M)\nfig, ax = plt.subplots(1)\nhs = ax.plot(Ms, energy[2], '-o', markersize=4,\n             markeredgecolor='none')\nleg = [hs[-1]]\nfor hi, hh in enumerate(hs):\n    h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4,\n                 color=hh.get_color(), markeredgecolor='none',\n                 alpha=0.66)\n    h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4,\n                 color=hh.get_color(), markeredgecolor='none',\n                 alpha=0.33)\n    if hi == len(hs) - 1:\n        leg.insert(0, h1[0])\n        leg.insert(0, h2[0])\nax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$')\nax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$',\n                'Corrected (subsample)'])\nfig.tight_layout()",
            "outputs": []
        }
    ]
}