{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "11e229bb",
            "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": "7e0fa88e",
            "cell_type": "markdown",
            "source": "The following example shows that an STFT can be indeed unitary:\n",
            "metadata": {}
        },
        {
            "id": "ee2a531e",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import ShortTimeFFT, windows\n\nm, hop, std = 36, 8, 5\ndesired_win = windows.gaussian(m, std, sym=True)\nSFT = ShortTimeFFT.from_win_equals_dual(desired_win, hop, fs=1/m,\n                                        fft_mode='twosided',\n                                        scale_to='unitary')\nnp.allclose(SFT.dual_win, SFT.win * SFT.m_num)  # check if STFT is unitary",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "True"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "c8e58be8",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "x1, x2 = np.tile([-1, -1, 1, 1], 5), np.tile([1, -1, -1, 1], 5)\nnp.sum(x1*x2) # scalar product is zero -> orthogonal signals",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "0"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "453f2314",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "np.sum(x1**2)  # scalar product of x1 with itself",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "20"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "60e5d18d",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "Sx11, Sx12 = SFT.spectrogram(x1), SFT.spectrogram(x1, x2)\nnp.sum(Sx12)  # STFT scalar product is also zero",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "-4.163336342344337e-16+0j  # may vary"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "7d421482",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "np.sum(Sx11)  # == np.sum(x1**2)\n\n# Do the plotting:",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "19.999999999999996  # may vary"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "3f5af8be",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "fg1, (ax11, ax12) = plt.subplots(1, 2, tight_layout=True, figsize=(8, 4))\ns_fac = np.sqrt(SFT.mfft)\n_ = fg1.suptitle(f\"Scaled Unitary Window of {m} Sample Gaussian with \" +\n                 rf\"{hop=}, $\\sigma={std}$, Scale factor: {s_fac}\")\nax11.set(ylabel=\"Amplitude\", xlabel=\"Samples\", xlim=(0, m))\nax12.set(xlabel=\"Frequency Bins\", ylabel=\"Magnitude Spectrum\",\n         xlim=(0, 15), ylim=(1e-5, 1.5))\nu_win_str = rf\"Unitary $\\times{s_fac:g}$\"\nfor x_, n_ in zip((desired_win, SFT.win*s_fac), ('Desired', u_win_str)):\n    ax11.plot(x_, '.-', alpha=0.5, label=n_)\n    X_ = np.fft.rfft(x_) / np.sum(abs(x_))\n    ax12.semilogy(abs(X_), '.-', alpha=0.5, label=n_)\nfor ax_ in (ax11, ax12):\n    ax_.grid(True)\n    ax_.legend()\nplt.show()",
            "outputs": []
        },
        {
            "id": "8149f07e",
            "cell_type": "markdown",
            "source": "Note that ``fftmode='twosided'`` is used, since we need sum over the complete\ntime frequency plane. Due to passing ``scale_to='unitary'`` the window\n``SFT.win`` is scaled by ``1/np.sqrt(SFT.mfft)``. Hence, ``SFT.win`` needs to\nbe scaled by `s_fac` in the plot above.\n",
            "metadata": {}
        }
    ]
}