Source code for torx.analysis.smoothing_m

"""Provides smoothing functionality."""
import numpy as np
import xarray as xr
from scipy.interpolate import interp1d
from torx.autodoc_decorators_m import autodoc_function

[docs] @autodoc_function def smooth_array(array: np.ndarray, axis: np.ndarray, block_length: int): """ Smooth a 1D array by averaging over the given block length. Block length should be picked sensibly since too small blocks have little effect and too big blocks will smooth out large scale structures. Can be used for easier interpretation of noisy signals. """ assert len(array.shape) == 1, "Only 1D arrays can be smoothed" assert len(array.shape) == len(axis.shape), "Axis and array dimensions do not match" # Check for common denominator if len(array) % block_length: blocked_array = np.zeros((len(array) // block_length + 1)) blocked_axis = np.copy(blocked_array) else: blocked_array = np.zeros((len(array) // block_length)) blocked_axis = np.copy(blocked_array) # Average array values for each block for i in range(len(blocked_array)): if i == len(blocked_array) - 1: # Last block possibly shorter than block_length blocked_array[i] = np.mean(array[i * block_length : -1]) blocked_axis[i] = np.mean(axis[i * block_length : -1]) else: blocked_array[i] = np.mean(array[i * block_length : (i + 1) * block_length]) blocked_axis[i] = np.mean(axis[i * block_length : (i + 1) * block_length]) return interp1d( blocked_axis, blocked_array, kind="linear", fill_value="extrapolate" )(axis)