{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "2d50682b",
            "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": "e9f0a6c7",
            "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": "18617dce",
            "cell_type": "markdown",
            "source": "Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by\n0.001 V**2/Hz of white noise sampled at 10 kHz.\n",
            "metadata": {}
        },
        {
            "id": "68049077",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "fs = 10e3\nN = 1e5\namp = 2*np.sqrt(2)\nfreq = 1234.0\nnoise_power = 0.001 * fs / 2\ntime = np.arange(N) / fs\nx = amp*np.sin(2*np.pi*freq*time)\nx += rng.normal(scale=np.sqrt(noise_power), size=time.shape)",
            "outputs": []
        },
        {
            "id": "41d7b807",
            "cell_type": "markdown",
            "source": "Compute and plot the power spectral density.\n",
            "metadata": {}
        },
        {
            "id": "4de8f33d",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "f, Pxx_den = signal.welch(x, fs, nperseg=1024)\nplt.semilogy(f, Pxx_den)\nplt.ylim([0.5e-3, 1])\nplt.xlabel('frequency [Hz]')\nplt.ylabel('PSD [V**2/Hz]')\nplt.show()",
            "outputs": []
        },
        {
            "id": "b1ad6361",
            "cell_type": "markdown",
            "source": "If we average the last half of the spectral density, to exclude the\npeak, we can recover the noise power on the signal.\n",
            "metadata": {}
        },
        {
            "id": "8d2122e8",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "np.mean(Pxx_den[256:])",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "0.0009924865443739191"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "0570f1b0",
            "cell_type": "markdown",
            "source": "Now compute and plot the power spectrum.\n",
            "metadata": {}
        },
        {
            "id": "1665f96f",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')\nplt.figure()\nplt.semilogy(f, np.sqrt(Pxx_spec))\nplt.xlabel('frequency [Hz]')\nplt.ylabel('Linear spectrum [V RMS]')\nplt.show()",
            "outputs": []
        },
        {
            "id": "a2bee42e",
            "cell_type": "markdown",
            "source": "The peak height in the power spectrum is an estimate of the RMS\namplitude.\n",
            "metadata": {}
        },
        {
            "id": "d30ee89a",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "np.sqrt(Pxx_spec.max())",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "2.0077340678640727"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "f513b229",
            "cell_type": "markdown",
            "source": "If we now introduce a discontinuity in the signal, by increasing the\namplitude of a small portion of the signal by 50, we can see the\ncorruption of the mean average power spectral density, but using a\nmedian average better estimates the normal behaviour.\n",
            "metadata": {}
        },
        {
            "id": "1c314d58",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "x[int(N//2):int(N//2)+10] *= 50.\nf, Pxx_den = signal.welch(x, fs, nperseg=1024)\nf_med, Pxx_den_med = signal.welch(x, fs, nperseg=1024, average='median')\nplt.semilogy(f, Pxx_den, label='mean')\nplt.semilogy(f_med, Pxx_den_med, label='median')\nplt.ylim([0.5e-3, 1])\nplt.xlabel('frequency [Hz]')\nplt.ylabel('PSD [V**2/Hz]')\nplt.legend()\nplt.show()",
            "outputs": []
        }
    ]
}