Search code examples
pythonsmoothing

Smoothing function with fixed end points (decreasing window size near boundary)


I would like either

  • a link to a smoothing function from existing library or
  • a 'reasonably performant' python function

that performs simple boxcar smoothing but with the catch that it accepts a boundary condition like this:

Suppose an array of length 9, with a rolling window of 5

target source indices


  1       1
  2     1 2 3
  3   1 2 3 4 5
  4   2 3 4 5 6
  5   3 4 5 6 7
  6   4 5 6 7 8
  7   5 6 7 8 9
  8     7 8 9
  9       9

So the rolling window get smaller near the boundaries, thereby preserving the end point values.

I have looked at: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter1d.html https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html


Solution

  • I would smooth the valid part first and then fix the boundary conditions. You could apply something like this:

    import numpy as np
    
    x = np.linspace(1, 9, 9)
    
    def rolling_average(x: np.ndarray, n: int) -> np.ndarray:
        boundary_values = n // 2
    
        y = np.zeros_like(x)
        y[boundary_values: -boundary_values] = np.convolve(x, np.ones(n)/n, mode='valid')
    
        for i in range(boundary_values):
            y[i] = np.mean(x[:i*2 + 1])
            y[-1 - i] = np.mean(x[-i*2 - 1:])
        return y
    
    print(rolling_average(x, 5))
    
    >>> [1. 2. 3. 4. 5. 6. 7. 8. 9.]