{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "d271065e",
            "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": "c3471b6a",
            "cell_type": "markdown",
            "source": "The examples will use several functions from `scipy.signal`.\n",
            "metadata": {}
        },
        {
            "id": "1da3de8d",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nfrom scipy import signal\nimport matplotlib.pyplot as plt",
            "outputs": []
        },
        {
            "id": "d2300e3e",
            "cell_type": "markdown",
            "source": "First we create a one second signal that is the sum of two pure sine\nwaves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz.\n",
            "metadata": {}
        },
        {
            "id": "294f3294",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "t = np.linspace(0, 1.0, 2001)\nxlow = np.sin(2 * np.pi * 5 * t)\nxhigh = np.sin(2 * np.pi * 250 * t)\nx = xlow + xhigh",
            "outputs": []
        },
        {
            "id": "f0ab2b3c",
            "cell_type": "markdown",
            "source": "Now create a lowpass Butterworth filter with a cutoff of 0.125 times\nthe Nyquist frequency, or 125 Hz, and apply it to ``x`` with `filtfilt`.\nThe result should be approximately ``xlow``, with no phase shift.\n",
            "metadata": {}
        },
        {
            "id": "8b377f35",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "b, a = signal.butter(8, 0.125)\ny = signal.filtfilt(b, a, x, padlen=150)\nnp.abs(y - xlow).max()",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "9.1086182074789912e-06"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "450b7f8b",
            "cell_type": "markdown",
            "source": "We get a fairly clean result for this artificial example because\nthe odd extension is exact, and with the moderately long padding,\nthe filter's transients have dissipated by the time the actual data\nis reached.  In general, transient effects at the edges are\nunavoidable.\n\nThe following example demonstrates the option ``method=\"gust\"``.\n\nFirst, create a filter.\n",
            "metadata": {}
        },
        {
            "id": "3d13af7e",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "b, a = signal.ellip(4, 0.01, 120, 0.125)  # Filter to be applied.",
            "outputs": []
        },
        {
            "id": "f4daeb5c",
            "cell_type": "markdown",
            "source": "`sig` is a random input signal to be filtered.\n",
            "metadata": {}
        },
        {
            "id": "142fd55b",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "rng = np.random.default_rng()\nn = 60\nsig = rng.standard_normal(n)**3 + 3*rng.standard_normal(n).cumsum()",
            "outputs": []
        },
        {
            "id": "e09ad19f",
            "cell_type": "markdown",
            "source": "Apply `filtfilt` to `sig`, once using the Gustafsson method, and\nonce using padding, and plot the results for comparison.\n",
            "metadata": {}
        },
        {
            "id": "c683c7a7",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "fgust = signal.filtfilt(b, a, sig, method=\"gust\")\nfpad = signal.filtfilt(b, a, sig, padlen=50)\nplt.plot(sig, 'k-', label='input')\nplt.plot(fgust, 'b-', linewidth=4, label='gust')\nplt.plot(fpad, 'c-', linewidth=1.5, label='pad')\nplt.legend(loc='best')\nplt.show()",
            "outputs": []
        },
        {
            "id": "cf4e769a",
            "cell_type": "markdown",
            "source": "The `irlen` argument can be used to improve the performance\nof Gustafsson's method.\n\nEstimate the impulse response length of the filter.\n",
            "metadata": {}
        },
        {
            "id": "c5ff6b16",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "z, p, k = signal.tf2zpk(b, a)\neps = 1e-9\nr = np.max(np.abs(p))\napprox_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))\napprox_impulse_len",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "137"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "463f3a3f",
            "cell_type": "markdown",
            "source": "Apply the filter to a longer signal, with and without the `irlen`\nargument.  The difference between `y1` and `y2` is small.  For long\nsignals, using `irlen` gives a significant performance improvement.\n",
            "metadata": {}
        },
        {
            "id": "ac53e761",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "x = rng.standard_normal(4000)\ny1 = signal.filtfilt(b, a, x, method='gust')\ny2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len)\nprint(np.max(np.abs(y1 - y2)))",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "2.875334415008979e-10"
                    },
                    "execution_count": null
                }
            ]
        }
    ]
}