<jupyter_start><jupyter_text>Filtering example in Pythonfor comparison with [Julia's version](Filtering%20example.ipynb)<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>1) Implementation of Exponential smoothing<jupyter_code>np.random.seed(0)
u = np.random.normal(size=1000).cumsum()
def smooth(u, a):
    y = np.zeros_like(u)
    
    y[0] = (1-a)*u[0]
    for k in range(1,len(u)):
        y[k] = a*y[k-1] + (1-a)*u[k]
    
    return y<jupyter_output><empty_output><jupyter_text>Plotwith Matplotlib<jupyter_code>plt.figure(figsize=(6,3))

a = 0.95
plt.plot(u);
plt.plot(smooth(u, a), color="C3", lw=5, alpha=0.5);
plt.legend(["original signal", "smoothed (a={})".format(a)]);<jupyter_output><empty_output><jupyter_text>2) Performance analysis<jupyter_code>np.random.seed(0)
u = np.random.normal(size=10**7).cumsum()
%time smooth(u, 0.9);
%timeit smooth(u, 0.9);<jupyter_output>4.37 s ± 63.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)<jupyter_text>almost ~**4.4 s** for 10 Mpts, that way more than in Julia (70 ms)  3) Alternative implementations  3a) Scipy's `lfilter`[scipy.signal.lfilter](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html)<jupyter_code>from scipy.signal import lfilter
np.random.seed(0)
u = np.random.normal(size=1000).cumsum()

y = lfilter([.05], [1, -0.95], u)

# check that it works
plt.plot(u);
plt.plot(y, color="C3", lw=5, alpha=0.5);<jupyter_output><empty_output><jupyter_text>Timing of lfilter<jupyter_code>np.random.seed(0)
u = np.random.normal(size=10**7).cumsum()
%timeit lfilter([.05], [1, -0.95], u)<jupyter_output>71.6 ms ± 933 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)<jupyter_text>**70 ms** for 10 Mpts, that's almost equal to Julia's naive version (70 ms)!   Numba  jithttp://numba.pydata.org/<jupyter_code>from numba import jit
@jit
def smooth_jit(u, a):
    y = np.zeros_like(u)
    
    y[0] = (1-a)*u[0]
    for k in range(1,len(u)):
        y[k] = a*y[k-1] + (1-a)*u[k]
    
    return y
smooth_jit(u, 0.9).shape
%timeit smooth_jit(u, 0.9);<jupyter_output>51.9 ms ± 1.31 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
StarcoderdataJupyterStructuredCleanDedup