{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "df670b15",
            "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": "8810fd09",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nrng = np.random.default_rng()",
            "outputs": []
        },
        {
            "id": "67081903",
            "cell_type": "markdown",
            "source": "Generate a test signal, a 2 Vrms sine wave at 50Hz corrupted by\n0.001 V**2/Hz of white noise sampled at 1024 Hz.\n",
            "metadata": {}
        },
        {
            "id": "05bc5a39",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "fs = 1024\nN = 10*fs\nnperseg = 512\namp = 2 * np.sqrt(2)\nnoise_power = 0.001 * fs / 2\ntime = np.arange(N) / float(fs)\ncarrier = amp * np.sin(2*np.pi*50*time)\nnoise = rng.normal(scale=np.sqrt(noise_power),\n                   size=time.shape)\nx = carrier + noise",
            "outputs": []
        },
        {
            "id": "40c871e5",
            "cell_type": "markdown",
            "source": "Compute the STFT, and plot its magnitude\n",
            "metadata": {}
        },
        {
            "id": "6b4b050e",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "f, t, Zxx = signal.stft(x, fs=fs, nperseg=nperseg)\nplt.figure()\nplt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud')\nplt.ylim([f[1], f[-1]])\nplt.title('STFT Magnitude')\nplt.ylabel('Frequency [Hz]')\nplt.xlabel('Time [sec]')\nplt.yscale('log')\nplt.show()",
            "outputs": []
        },
        {
            "id": "908f0929",
            "cell_type": "markdown",
            "source": "Zero the components that are 10% or less of the carrier magnitude,\nthen convert back to a time series via inverse STFT\n",
            "metadata": {}
        },
        {
            "id": "5b720b4b",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "Zxx = np.where(np.abs(Zxx) >= amp/10, Zxx, 0)\n_, xrec = signal.istft(Zxx, fs)",
            "outputs": []
        },
        {
            "id": "10155c53",
            "cell_type": "markdown",
            "source": "Compare the cleaned signal with the original and true carrier signals.\n",
            "metadata": {}
        },
        {
            "id": "293780e8",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "plt.figure()\nplt.plot(time, x, time, xrec, time, carrier)\nplt.xlim([2, 2.1])\nplt.xlabel('Time [sec]')\nplt.ylabel('Signal')\nplt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier'])\nplt.show()",
            "outputs": []
        },
        {
            "id": "956ee0da",
            "cell_type": "markdown",
            "source": "Note that the cleaned signal does not start as abruptly as the original,\nsince some of the coefficients of the transient were also removed:\n",
            "metadata": {}
        },
        {
            "id": "13398590",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "plt.figure()\nplt.plot(time, x, time, xrec, time, carrier)\nplt.xlim([0, 0.1])\nplt.xlabel('Time [sec]')\nplt.ylabel('Signal')\nplt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier'])\nplt.show()",
            "outputs": []
        }
    ]
}